0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

転機となった一年の出来事を振り返るAdvent Calendar 2024

Day 13

【Rspec】ケース別、よく使った書き方まとめ

Last updated at Posted at 2024-12-21

ネタ切れ感満載ですが

1.before doとlet

コンテキストごとに同じインスタンスを作るが、一部のデータは可変にしたいとき

# これを
context '1' do
  let(:hoge) { create(:hoge, fuga_id: 100) }
end

context '2' do
  let(:hoge) { create(:hoge, fuga_id: 200) }
end

# こう
let(:fuga_id) { 100 }

before do
  create(:hoge, fuga_id: fuga_id)
end

context '1' do
end

context '2' do
  let(:fuga_id) { 200 }
end

2.Timecop

テスト実行時に現在時刻を固定したいとき

before do
  Timecop.freeze(Time.local(2024, 12, 21))
end

after do
  Timecop.return
end

it "2024であること" do
  expect(Time.now.year).to eq(2024)
end

3.allow

メソッドをモックしたいとき

it "100を返すこと" do
  allow(HogeModel).to receive(:hoge_method).and_return(100)
  expect(HogeModel.new.hoge_method).to eq 100
end

4. and_return

モックしたメソッドが複数回呼ばれていて、返り値を毎回指定したいとき

  allow(Order).to receive(:find).and_return(1, 2)

  expect(Order.find).to eq(1)
  expect(Order.find).to eq(2)
end

おわりに

テストデータを作るのが一番大変かも

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?