LoginSignup
0
0

More than 3 years have passed since last update.

RSpec コントローラーテストの書き方

Posted at

前提

・deviseが導入されています
・今回書くテストの内容について
  ・ユーザーがログインしていれば、正しく表示されること

app/controllers/posts_controller.rb
  class PostsController < ApplicationController
    before_action: authenticate_user!

    def index
      @posts = Post.all
    end
  end

ファイルの作成・役割について

①spec配下にrequests, factoriesフォルダを作成

・spec/requests/posts_request.rbを作成
  →テストの内容を記述するファイル

・spec/factories/user.rb
・spec/factories/post.rbを作成
  →userとpostに関するダミーデータを作成するファイル

②FactoryBotを使えるようにするためにspec配下にsupportフォルダとfactory_bot.rbファイルを作成

spec/support/factroy_bot.rb
RSpec.configure do |config|
  config.include FactoryBot::Syntax::Method #FactoryBotのため
  config.include Devise::Test::IntegrationHelper, type: :request #deviseのsign_inメソッドが使えるようになる
end

次にrails_helper.rbの編集

spec/rails_helper.rb
require 'spec_helper'
...
require 'rspec/rails'
require 'support/factroy_bot'  #←この記述によってFactroyBotを使用できる

ダミーデータの作成

spec/factories/user.rb
FactoryBot.define do
  factory :user do 
    email { Faker::Internet.email }
    name { "testuser1" }
    password { "password" }
    password_confirmation { "password" }
  end 
end
spec/factories/post.rb
FactroyBot.defind do
  factory :post do
    body { Faker::Lorem.charactors(number: 15) } #15文字のダミー文を作成
  end
end

テストコードの作成

spec/requests/post_spec.rb
require 'rails_helper'

RSpec.describe 'post_controllerのテスト', type: :request do
  let(:user) { create(:user) }
  let(:post) { create(:post) }
  describe 'ログイン済みの場合' do
    before do
      sign_in user
      get posts_path
    end

    it '投稿一覧ページへのリクエストは200 okとなること' do
      expect(response.status).to eq 200
    end

    it 'ページタイトルが正しく表示されていること' do
      expect(response.body).to include('投稿一覧')
    end
  end

  describe "ログインしていない場合" do
    before do 
      get posts_path
    end

   it 'リクエストが401となること' do
     expect(response.status).to eq 401
   end

   it 'タイトルが表示されない' do
     expect(response.body).to_not include("投稿一覧")
   end
  end
end

あとはRSpecを動かしてみるのみ!

$ rspec spec/requests

最後に

初心者中の初心者の記事なので、十中八九ミスがあると思います。
気づかれた方がおられたら、教えていただけるととてもありがたいです!

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