[英]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
失败/错误:期望{response}。更改为{current_user.reload.email} .to('aieie@brazorf.com')预期结果已更改为“ aieie@brazorf.com”,但未更改
How can I test that a call to a controller PUT/update action actually change the Model attributes? 如何测试对控制器PUT /更新操作的调用是否确实更改了模型属性?
edit 编辑
If I inspect and evaluate current_user
with binding.pry before and after the failing test, I see it actually changes. 如果在失败测试之前和之后,使用binding.pry检查并评估
current_user
,我会发现它实际上发生了变化。 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. 实际上,将请求语句(GET,PUT,POST和DELETE)放置在it块内是很好的 ,这样我们就应该能够使用rspec expec功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.