RailsチュートリアルのテストをRspecで書いてみた[第7章]

はじめに

今回はRspecの学習の一環として、RailsチュートリアルのテストをRspecで書いていきます。
至らない点があるかもしれませんが、その際はコメントにてご指摘をお願いします。

各種バージョン

Ruby 2.7.0
Rails 6.0.3.3
Rspec 3.9
Capybara 3.33.0
Factory_bot_rails 6.1.0

第7章

リスト7.23: 無効なユーザー登録に対するテスト

spec/system/users_signups_spec.rb

require 'rails_helper'
RSpec.describe "UsersSignups", type: :system do
  scenario 'Don\'t create new data when user submits invalid information' do
    visit signup_path
    fill_in 'Name', with: ' '
    fill_in 'Email', with: 'user@invalid'
    fill_in 'Password', with: 'foo'
    fill_in 'Confirmation', with: 'bar'
    click_on 'Create my account'
    aggregate_failures do
      expect(current_path).to eq users_path
      expect(page).to have_content 'Sign up'
      expect(page).to have_content 'The form contains 4 errors'
    end
  end
end

リスト7.31: 有効なユーザー登録に対するテスト

spec/factories/user.rb

FactoryBot.define do
  factory :user do
    name { "TestUser" }
    sequence(:email) { |n| "test#{n}@example.com" } 
    password { "foobar" }
    password_confirmation { "foobar" }
  end
end
spec/requests/users_request_spec.rb

require 'rails_helper'

RSpec.describe "Users", type: :request do
・・・
  describe "POST /users" do
    let(:user) { FactoryBot.attributes_for(:user) }  #<= attributes_forはハッシュの形で返してくれる。
    it "adds new user with correct signup information" do
      aggregate_failures do
        expect do
          post users_path, params: { user: user } # <= paramsの中身はハッシュの形
        end.to change(User, :count).by(1)
        expect(response).to have_http_status(302)
        expect(response).to redirect_to user_path(User.last)
      end
    end
  end
end

補足

paramsにはハッシュの形で値が渡されるので、「attributes_for」を使用しています。

changeマッチャでデータ数が変更されているかを確認しています。

登録後、リダレクトするので「have_http_status」を使用して確認しました。
また、リダイレクト先のURLを調べる際、「User.last」を使用すれば良いと気付くのに手間取りました...

リスト7.32: flashをテストするためのテンプレート

spec/system/users_signups_pec.rb

require 'rails_helper'

RSpec.describe "UsersSignups", type: :system do
・・・
  scenario 'Create new data when user submits valid information' do
    visit signup_path
    fill_in 'Name', with: 'Example User'
    fill_in 'Email', with: 'user@example.com'
    fill_in 'Password', with: 'password'
    fill_in 'Confirmation', with: 'password'
    click_on 'Create my account'
    aggregate_failures do
      expect(current_path).to eq user_path(User.last)
      expect(has_css?('.alert-success')).to be_truthy
      visit current_path # <= 再読み込みを再現しています。
      expect(has_css?('.alert-success')).to be_falsy
    end
  end
end

補足

「current_path」で現在のURLを取得できます。

「has_css?」でview内のCSSを検索し、「be_truthy」,「be_falsy」で存在しているかを調べています。