※本サイトで紹介している商品・サービス等の外部リンクには、アフィリエイト広告が含まれる場合があります。
contextとletを使って、それぞれテストを書く
前回の続きで、↓を書き換えていく
RSpec.describe Article, type: :model do
it 'タイトルと内容が入力されていれば、記事を保存できる' do
user = User.create!({
email: 'test@example.com',
password: 'password'
})
article = user.articles.build({
title: Faker::Lorem.characters(number: 10),
content: Faker::Lorem.characters(number: 300)
})
expect(article).to be_valid
end
end
context
やlet
を使うと、一目みたときに「このテストでなにを確認したいのか」すぐわかるようにできる
context(bofore)でテストを書く
「◯◯の状況である場合、●●が出来る」
it 'タイトルと内容が入力されていれば、記事を保存できる' do
↑のような前提条件を作るときにcontext
を使う
RSpec.describe Article, type: :model do
context 'タイトルと内容が入力されている場合' do
end
「タイトルと記事がある場合」が前提条件になる
context
では「〜場合」と書く
そして、it
以降のコードをすべて中に入れる
RSpec.describe Article, type: :model do
context 'タイトルと内容が入力されている場合' do
it '記事を保存できる' do
user = User.create!({
email: 'test@example.com',
password: 'password'
})
article = user.articles.build({
title: Faker::Lorem.characters(number: 10),
content: Faker::Lorem.characters(number: 300)
})
expect(article).to be_valid
end
end
end
前提条件を実現させるためのbefore
を使う
「タイトルと記事がある」という前提を実現させるため、ダミーデータを中に入れる
RSpec.describe Article, type: :model do
context 'タイトルと内容が入力されている場合' do
before do
user = User.create!({
email: 'test@example.com',
password: 'password'
})
@article = user.articles.build({
title: Faker::Lorem.characters(number: 10),
content: Faker::Lorem.characters(number: 300)
})
end
it '記事を保存できる' do
expect(@article).to be_valid
end
end
end
article
がbefore do
の中に入ってしまい、expect(article).to be_valid
で使うことが出来ない
→ インスタンス変数@article
にしておく
context
を使うほうが、前提条件と、なにを確認したいのかが一目でわかりやすい
ターミナルを開いて、前回と同じように実行する
bundle exec rspec spec/models/article_spec.rb
テスト成功!

letでテストを書く
rspecでは変数を宣言するときにlet
を使い、前提条件を作るときもlet
が使える
RSpec.describe Article, type: :model do
context 'タイトルと内容が入力されている場合' do
let!(:user) do
user = User.create!({
email: 'test@example.com',
password: 'password'
})
end
let!(:article) do
article = user.articles.build({
title: Faker::Lorem.characters(number: 10),
content: Faker::Lorem.characters(number: 300)
})
end
it '記事を保存できる' do
expect(article).to be_valid
end
end
end
let
を使うときは@
(インスタンス変数)をつけなくても良い(:user)
とは、user =
と同じ意味let
を使うとき、before
は使わない
ターミナルを開いて、前回と同じように実行する
bundle exec rspec spec/models/article_spec.rb
テスト成功!

#DAY13