我正在寻找this的方法,但是在请求规范中。我需要登录并注销double
或instance_double
到Devise而不是实际的ActiveModel / ActiveRecord。
使用维基页面中的代码:
module RequestSpecHelpers
def sign_in(user = double('user'))
if user.nil?
allow(request.env['warden']).to receive(:authenticate!).and_throw(:warden, {:scope => :user})
allow(controller).to receive(:current_user).and_return(nil)
else
allow(request.env['warden']).to receive(:authenticate!).and_return(user)
allow(controller).to receive(:current_user).and_return(user)
end
end
end
我收到此错误:undefined method 'env' for nil:NilClass
我看到了this question和this wiki,但是如果我想使用用户的双打那么这两个不起作用。我正在使用最后一个,与真实用户一起工作正常,但是使用双倍它不会记录它。
测试:
RSpec.describe 'new shipment', type: :request do
describe 'authenticated as user' do
before do
@user = double(:user, id: 1, email: 'user@gmail.com', password: 'password',
id_card: '4163649-1', first_name: 'Jane', last_name: 'Doe')
sign_in @user
end
end
end
如果我包括:
RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :requests
end
我收到此错误:
Failure/Error: @request.env['action_controller.instance'] = @controller
NoMethodError:
undefined method `env' for nil:NilClass
# /root/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:40:in `setup_controller_for_warden'
如果我这样做,login_as
方法不会失败,但它并没有真正记录用户。所以当我尝试访问具有before_action :authenticate_user!
回调的路径时,它会失败。< / p>
这是我的代码基于他的回答:
require 'rails_helper'
RSpec.describe 'new shipment', type: :request do
describe 'authenticated as user' do
include Warden::Test::Helpers
before(:each) do
Warden.test_mode!
#stub more methods as needed by the pages you are testing
user = instance_double(User, to_key: 1, authenticatable_salt: 'example')
login_as(user, scope: 'user')
end
it 'returns 200 Ok' do
get new_shipment_path
expect(response).to have_http_status(:ok)
end
end
end
这是运行rspec
时的响应:
1) new shipment authenticated as user returns 200 Ok
Failure/Error: expect(response).to have_http_status(:ok)
expected the response to have status code :ok (200) but it was :found (302)
# ./spec/requests/shipments_requests_spec.rb:41:in `block (3 levels) in <top (required)>'
正如您所看到的那样,不允许我访问重定向的路径,这是不允许用户访问路径时的常见行为。
我更改了instance_double
保存在数据库中的真实User
此方法正常运行:
# only changed this line in the before hook
user = User.create(email: 'user@gmail.com', password: 'password',id_card: '4163649-1', first_name: 'Jane', last_name: 'Doe')
结果:
Finished in 3.23 seconds (files took 33.47 seconds to load)
1 example, 0 failures
答案 0 :(得分:3)
听起来你正在使用Devise 3.x(因为Devise::TestHelpers
已在设计4中重命名),Devise::TestHelpers
仅用于控制器规范。
如果您可以升级到设计4,则它具有用于请求规范和控制器测试的单独帮助程序。这只是一个非常薄的包裹着warden provides的东西,它隐藏了env的所有混乱。
使用double时会出现一些额外的复杂问题 - 你需要设置各种方法来设计你可能没有意识到的调用。
以下为我工作
describe 'example' do
include Warden::Test::Helpers
before(:each) do
Warden.test_mode!
#stub more methods as needed by the pages you are testing
user = instance_double(User, to_key: 1, authenticatable_salt: 'example')
login_as(user, scope: 'user')
end
end