[英]how to login in with devise using rspec
This is my rspec file 这是我的rspec文件
it "assigns all tool_cvt_remote_focus as @tool_cvt_remote_focus" do
post "/users/sign_in", {:username => 'user', :password => "test"}
end
rake routes 耙路
users/sessions#new {:locale=>"jp"} new_user_session_en GET /users/sign_in(.:format)
The error on console with POST method 使用POST方法的控制台上的错误
Failure/Error: post "/users/sign_in", {:user => 123}
ActionController::UrlGenerationError:
No route matches {:action=>"/users/sign_in", :controller=>"users", :user=>"123"}
The error with GET method GET方法的错误
Failure/Error: get "/users/sign_in", {:username => 'user', :password => "test"}
Okay, I did some research and with Devise and Rspec and got your test working, albeit with some refactoring. 好的,尽管进行了一些重构,我还是对Devise和Rspec进行了一些研究,并使您的测试正常进行。
What I had to do was use the Devise helpers, to do that I had to add that capability into my spec_helper file: 我要做的是使用Devise帮助器,为此我必须将该功能添加到我的spec_helper文件中:
require 'devise'
RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
end
Then I had to refactor your test to use these new Devise helper methods, otherwise Devise would throw me an error about trying to skip over the router. 然后,我不得不重构您的测试以使用这些新的Devise辅助方法,否则Devise会给我一个有关跳过路由器的错误。
require 'rails_helper'
RSpec.describe Devise::SessionsController, :type => :controller do
it "assigns all tool_cvt_remote_focus as @tool_cvt_remote_focus" do
@request.env["devise.mapping"] = Devise.mappings[:user]
user = User.create(
username: 'user',
password: 'test'
)
sign_in :user, user
end
end
Now, the way I created the user is not a best practice. 现在,我创建用户的方法不是最佳实践。 From what I could tell online you are supposed to use FactoryGirl to to create the user because that is less fragile.
从网上我可以告诉您的是,您应该使用FactoryGirl来创建用户,因为它不那么脆弱。 However, as I have never used FactoryGirl and just wanted to give you the simplest solution possible, I decided not to include it.
但是,由于我从未使用过FactoryGirl,只是想为您提供最简单的解决方案,因此我决定不包括它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.