RSpec学習メモ [RSpec編] 03_SystemSpec
<システムスペック> 参考記事:https://qiita.com/jnchito/items/c7e6e7abf83598a6516d
システムスペックを使用するには、以下のgemが必要である。
・capybara
・webdrivers
---------------------------------------------------------------------------------------
<Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }>
<spec/rails_helper.rb>
# 省略
# Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
上記のコメントアウトを外すことで、spec/support配下のRSpecファイルを読み込むように設定することができる。
---------------------------------------------------------------------------------------
<--format documentation>
<.rspec>
--format documentation
上記を記載することで、テスト実行の度に見やすいフォーマットでテスト結果を表示してくれる。
---------------------------------------------------------------------------------------
<config.filter_run_when_matching :focus>
<spec/spec_helper.rb>
# 省略
config.filter_run_when_matching :focus
この設定により、RSpec.describe SampleController, type: :request, focus: true doのように設定したspecファイルに対してのみ、テストを実行するようになる。
特定のテストだけを実行したい時に使用する。
---------------------------------------------------------------------------------------
<テストを書いて学んだこと>
<spec/system/user_sessions_spec.rb>
require 'rails_helper'
RSpec.describe "UserSessions", type: :system, focus: true do
let(:user) { create(:user) }
describe 'ログイン前' do
context 'フォームの入力値が正常' do
it 'ログインに成功する' do
visit login_path
fill_in 'Email', with: user.email
fill_in 'Password', with: 'password'
click_button 'Login'
expect(page).to have_content 'Login successful'
expect(current_path).to eq root_path
end
end
end
end
※fill_in ‘Password’, with: user.passwordにするとテストは通らない。
[原因] Sorceryを使用していて、Usersテーブルにはpasswordというカラムがなく、crypted_passwordカラムを取得するしかないが、内容はハッシュ化されているので画面でログインする際の情報としては利用できない。
---------------------------------------------------------------------------------------
<解答例から学んだこと>
<letとlet!の違い>
let は 最初にメソッドが呼ばれた時 に評価される。
let! は letが遅延評価であるのとは違い、各サンプルが実行される前に評価される。
<create_list>
FactoryBotから複数のインスタンスを作成することができる。
task_list = FactoryBot.create_list(:task, 3)