57
52

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rspecでupdateのテストを通せない初心者が疑うべきこと

Posted at

例えばこんなspecを書いていたとする.
(ちなみに雰囲気で書いたので色々と足りなかったりするがお察しいただけると幸いです)

it '名前が更新される' do
  put path, params: { name: 'new_name!' }
  expect(user.name).not_to eq 'old_name'
end

これだといくら実装が正しくてもテストは通らない.
なぜなら,DBの値が更新されてもすでに読み込まれた user インスタンスの値は更新されないからだ.

インスタンスの値を更新するには user.reload とすればよい.
これを用いると上の例は次のように修正できる.

it '名前が更新される' do
  put path, params: { name: 'new_name!' }
  expect(user.reload.name).not_to eq 'old_name'
end
57
52
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
57
52

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?