Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
41
Help us understand the problem. What is going on with this article?

More than 1 year has passed since last update.

@ry_2718

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

例えばこんな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
41
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
41
Help us understand the problem. What is going on with this article?