LoginSignup
6
7

More than 1 year has passed since last update.

[Rails, devise, RSpec] テストでログインする

Last updated at Posted at 2017-09-06

ここに書いてある。
feature spec でも使用できた。

require 'rails_helper'

RSpec.feature '...', type: :feature do
  include Devise::Test::IntegrationHelpers

  given(:current_user) { create :user }

  before do
    sign_in current_user
  end

  ...
end

便利かもしれない使い方

spec/rails_helper.rb

Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }

のコメントアウトを外して、

spec/support/sign_in.rb
shared_examples :sign_in do
  include Devise::Test::IntegrationHelpers

  let(:current_user) { create :user }

  before do
    sign_in current_user
  end
end

ってファイルを追加すると、

require 'rails_helper'

RSpec.feature '...', type: :feature do
  context 'ログイン後' do
    include_examples :sign_in

    scenario '...' do
      current_user # ログイン済みのユーザー
    end
  end
end

こんな感じに使える

6
7
0

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
6
7