在factory.rb中:
FactoryBot.define do
factory :user do
email { Faker::Internet.email }
username { Faker::FunnyName.name.downcase.gsub(/\s/,"_") }
first_name { Faker::Name.name }
last_name { Faker::Name.name }
password "password"
password_confirmation "password"
confirmed_at Date.today
roles { [ FactoryBot.create(:role) ] }
factory :admin do
roles { [ FactoryBot.create(:admin_role) ] }
end
end
factory :role do
name { Faker::Job.field.downcase }
factory :admin_role do
name "admin"
end
end
在support/controller_macros.rb
module ControllerMacros
def login_admin
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:admin]
admin = FactoryBot.create(:admin)
sign_in :user, admin
end
end
end
在rails_helper.rb中:
config.include Devise::Test::ControllerHelpers, type: :controller
config.extend ControllerMacros, type: :controller
在filters_controller_spec.rb中:
require 'rails_helper'
describe GlobalFiltersController, type: :controller do
describe "GET #new" do
context "when model is an :ActiveRecord object" do
login_admin
it "should have a current_user" do
expect(subject.current_user).to_not eq(nil)
end
但是,我在Rspec中得到以下结果:
FiltersController GET #new when model is an :ActiveRecord object should have a current_user
Failure/Error: expect(subject.current_user).to_not eq(nil)
ArgumentError:
uncaught throw :warden
登录失败。但是在我的应用程序中,它不会失败。我不确定在此测试中我做错了什么。当我使用Devise时如何通过测试?