繁体   English   中英

Rails-Rspec:测试PUT更新以实际更改模型属性

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

我有以下内容:

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
...

上面的代码中被注释掉的期望失败,并显示以下消息:

失败/错误:期望{response}。更改为{current_user.reload.email} .to('aieie@brazorf.com')预期结果已更改为“ aieie@brazorf.com”,但未更改

如何测试对控制器PUT /更新操作的调用是否确实更改了模型属性?

编辑

如果在失败测试之前和之后,使用binding.pry检查并评估current_user ,我会发现它实际上发生了变化。 测试仍然失败

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

您应该在期望之前重新加载对象:

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

或另一种方式:

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

您已更改了以下期望代码,以利用从和进行更改

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

实际上,将请求语句(GET,PUT,POST和DELETE)放置在it块内是很好的 ,这样我们就应该能够使用rspec expec功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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