【问题标题】:Rails - Rspec: test PUT update to actually change Model attributesRails - Rspec:测试 PUT 更新以实际更改模型属性
【发布时间】:2017-09-01 07:37:43
【问题描述】:

我有以下几点:

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}.to 更改{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

【问题讨论】:

  • 可能是验证失败了?
  • 我在这里注意到的另一件事是,发布请求应该在块内,如 stackoverflow.com/a/41730044/2767755
  • 不,最后一次测试通过
  • 好的,我现在看到了。

标签: ruby-on-rails rspec


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你已经改变了你的期望代码,如下所示,以利用 change, from and to,

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

    其实把请求语句(GET, PUT, POST and DELETE)放在it块里面是很好的,这样我们就可以使用rspec expec特性了.

    【讨论】:

    • 我得到了同样的expected result to have changed to "aieie@brazorf.com", but did not change失败
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多