50
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

type: :requestのテストでsign_in/sign_outする

Last updated at Posted at 2017-03-15

コントローラのテストを書いていて、リクエストの前にユーザログイン状態にしたいとうことはよくあると思います。
type: :controllerでは以下のようにDevise::TestHelpersを読み込むことでテスト内でログインさせることができます。

rails-helper.rb
RSpec.configure do |config|
  ...
  config.include Devise::TestHelpers, :type => :controller
end
some_controller_spec.rb
require 'rails_helper'
RSpec.describe SomeController, type: :controller do
  before do
    user = create(:user) #FactoryGirl
    sign_in user
  end
end

しかしながら、type: :requestではDevise::TestHelpersは使えないので独自にsupport内にHelperを書いて読み込むようにすれば上手くいきました。

spec/support/request_spec_helper.rb
module RequestSpecHelper

  include Warden::Test::Helpers

  def self.included(base)
    base.before(:each) { Warden.test_mode! }
    base.after(:each) { Warden.test_reset! }
  end

  def sign_in(resource)
    login_as(resource, scope: warden_scope(resource))
  end

  def sign_out(resource)
    logout(warden_scope(resource))
  end

  private

  def warden_scope(resource)
    resource.class.name.underscore.to_sym
  end

end
rails-helper.rb
RSpec.configure do |config|
  ...
  Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } #support directoryをrequire
  config.include RequestSpecHelper, type: :request #type: :requestのときにRequestHelperをinclude
end
some_controller_spec.rb
require 'rails_helper'
RSpec.describe SomeController, type: :request do
  before do
    user = create(:user) #FactoryGirl
    sign_in user #Success!!
  end
end
50
40
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
50
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?