我将rspec从版本2升级到3.之后我遇到了这个问题:
Failures:
1) AlbumsController GET #edit
Failure/Error: sign_in_and_switch_schema @user
NoMethodError:
undefined method `env' for nil:NilClass
# ./spec/support/auth_helpers.rb:10:in `sign_in_and_switch_schema'
# ./spec/controllers/albums_controller_spec.rb:12:in `block (2 levels) in <top (required)>'
spec_helper.rb 包含:
RSpec.configure do |config|
# most omitted
config.include Warden::Test::Helpers
config.include Devise::TestHelpers, type: :controller
end
albums_controller_spec.rb :
describe AlbumsController do
let(:album) { create(:album) }
before(:all) do
@user = create :user
end
before(:each) do
sign_in_and_switch_schema @user
end
after(:all) do
destroy_users_schema @user
destroy_user @user
end
# describe's part omitted
end
auth_helpers.rb 部分发生了错误:
def sign_in_and_switch_schema(user)
# binding.pry
@request.env["devise.mapping"] = Devise.mappings[:user] # <- error line
sign_in :user, user
Apartment::Tenant.switch(user.username)
end
我正在寻找另一个同样的Q&amp; A,但没有找到任何帮助。如果我应该包含更多内容,请告诉我。提前致谢。
答案 0 :(得分:7)
解决方案是添加到spec_helper.rb:
RSpec.configure do |config|
config.infer_spec_type_from_file_location!
end
答案 1 :(得分:3)
根据Devise TestHelper documentation,您应该只使用
@request.env["devise.mapping"] = Devise.mappings[:user]
当您测试继承Devise控制器的控制器时。我猜AlbumsController并不是从Devise Controller继承的。我认为你不需要那条线进行这些测试。
尝试删除此行或创建另一个仅执行sign_in和开关的辅助方法:
def simple_sign_in_and_switch(user)
sign_in :user, user
Apartment::Tenant.switch(user.username)
end
然后在测试用例中调用该方法:
before(:each) do
simple_sign_in_and_switch_schema @user
end
如果这样做有效,请尝试完全删除故障线并运行完整的测试套件,看看是否需要在其他地方使用。如果是,则在另一个方法中提取该行,并仅在需要时使用它。