我正在尝试测试我的控制器是否可以被未注册用户访问。我使用的是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