简体   繁体   中英

Rails - Rspec: test PUT update to actually change Model attributes

I have the following:

let(:update_request) { put "/api/v3/account/profile.json", attributes, credentials }

describe "PUT 'update'" do
  before { update_request }

  context "updating normal attributes (no password)" do
    let(:attributes) {
      {
        profile: { first_name: 'John', phone: '02 21231321', email: 'aieie@brazorf.com' }
      }
    }

    it do
      aggregate_failures do
        # expect{response}.to change{current_user.reload.email}.to('aieie@brazorf.com')
        expect(response).to be_success
        expect(current_user.reload.first_name).to eq('John')
        expect(current_user.reload.phone).to eq('02 21231321')
        expect(current_user.reload.email).to eq('aieie@brazorf.com')
      end
    end
  end
...

The expectation that in the code above is commented out fails with the following message:

Failure/Error: expect{response}.to change{current_user.reload.email}.to('aieie@brazorf.com') expected result to have changed to "aieie@brazorf.com", but did not change

How can I test that a call to a controller PUT/update action actually change the Model attributes?

edit

If I inspect and evaluate current_user with binding.pry before and after the failing test, I see it actually changes. The test still fails tho

binding.pry
expect{response}.to change{current_user.reload.email}.to('aieie@brazorf.com')
binding.pry

You should reload your object before expectations:

current_user.reload
expect(current_user.email).to eq('new@ya.com')

Or another way:

it do
  expect do
    subject
    user.reload
  end.to change(user, :email).from('test@ya.com').to('new@ya.com')
end

You have change your expectation code like below to make use of change, from and to ,

expect {
  put "/api/v3/account/profile.json", attributes, credentials
}.to change{current_user.reload.email}.to('aieie@brazorf.com')

Actually it's good to place request statements(GET, PUT, POST and DELETE) inside the it block , so that we should be able to make use rspec expec features.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM