LoginSignup
1
1

More than 3 years have passed since last update.

【RSpec】authenticate_user!を使用したときのRSpecへの副作用をFactoryBotで解消する

Last updated at Posted at 2020-05-05

概要

Railsアプリのコントローラーで「authenticate_user!」を、
ログイン済みでないとアクセスしてほしくないアクションに設定しました。

そしてRSpecでコントローラーのテストを実施しようとした際に、
普通にアクションごとにテストコードを書くと「authenticate_user!」の影響でエラーになります。

それをFactoryBotを使って回避する方法を備忘録としてまとめます。

Gemをインストール

group :development, :test do
gem 'factory_bot_rails'
gem 'rspec-rails'
end

rails_helper.rbを編集

rails_helper.rb
RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
  config.include Devise::TestHelpers, type: :controller
end

spec/factories/user.rbを作成

user.rb
FactoryBot.define do
  factory :user do
    name                    { "testname" }
    email                   { "aaa@gmail.com" }
    password                { "00000000" }
    encrypted_password      { "00000000" }
  end
end

spec/controllers/posts_controller_spec.rbを作成

今回は例でposts controllerのnewアクションに実装します。

posts_controller_spec.rb
require 'rails_helper'

describe PostsController do
  describe 'GET #new' do
    # ユーザを生成
    before do
      user = FactoryBot.create(:user)
      # 作ったユーザでログイン
      sign_in user
    end

    it "ビューに正しく遷移するか" do
      get :new
      expect(response).to render_template :new
    end
  end

end

これで「authenticate_user!」をコメントアウトしなくともエラーが出なくなります。

以上です。

間違い等ありましたらご指摘いただけますと幸いです。

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