# spec/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 # sign_in(scope, resource)
end
end
def login_user
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
user = FactoryBot.create(:user)
user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the "confirmable" module
sign_in user
end
end
end
require_relative "support/controller_macros" # or require_relative "./controller_macros' if write in `spec/support/devise.rb"
RSpec.configure do |config|
# Deviseのバージョンが4.1.2以上の時は以下のようにします。
config.include Devise::Test::ControllerHelpers, :type => :controller
# Deviseのバージョンが4.1.1以下の時は上をコメントアウトして、以下の記述にします。
# config.include Devise::TestHelpers, :type => :controller
config.extend ControllerMacros, :type => :controller
end
コントローラーspecでの記述
とうとうコントローラーspecでの記述になります。
describe MyController do
login_admin
it "should have a current_user" do
# note the fact that you should remove the "validate_session" parameter if this was a scaffold-generated controller
expect(subject.current_user).to_not eq(nil)
end
it "should get index" do
# Note, rails 3.x scaffolding may add lines like get :index, {}, valid_session
# the valid_session overrides the devise login. Remove the valid_session from your specs
get 'index'
response.should be_success
end
end