我正在尝试测试我的控制器,以便从未注册用户进行访问。我使用devise(3.3.0)和rspec(3.0.0)。
spec/controllers/dares_controller_spec.rb
require 'rails_helper'
describe DaresController do
let(:challenger) { create(:user) }
let(:acceptor) { create(:user) }
let(:challenge) { create(:challenge) }
let(:dare) { create(:dare) }
let(:user) { create(:user) }
describe 'Guest access to dares' do
describe 'GET #show' do
it "redirects to root" do
get :show, id: dare.id, challenge_id: challenge.id
expect(response).to require_login
end
end
end
end
在控制器中:
dares_controller.rb
before_action :authenticate_user!
def show
end
我收到以下错误:
Failures:
1) DaresController Guest access to dares GET #show redirects to root
Failure/Error: get :show, id: dare.id, challenge_id: challenge.id
NoMethodError:
undefined method `authenticate!' for nil:NilClass
# ./spec/controllers/dares_controller_spec.rb:16:in `block (4 levels) in <top (required)>'
我尝试添加
RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
end
到我的spec_helper / rails_helper但它没有解决问题。我用Google搜索了几个小时的解决方案,两者似乎都有所帮助。
匹配器 - require_login
RSpec::Matchers.define :require_login do |expected|
match do |actual|
expect(actual).to redirect_to Rails.application.routes.url_helpers.new_user_session_path
end
failure_message do |actual|
"expected to require login to access the method"
end
failure_message_when_negated do |actual|
"expected not to require login to access the method"
end
description do
"redirect to the login form"
end
end
答案 0 :(得分:3)
更改此行:
描述DaresController做
到这一个:
RSpec.describe DaresController,输入:: controller do
由于您将spec_helper或rails_helper配置为:
config.include Devise::TestHelpers, type: :controller
您应该设置正确的规范type
才能正常工作。它是rspec~3中的rspec行为