2

我正在尝试在控制器上测试它是否在更新批量分配保护属性时引发错误。

expect do 
  post :create, account: {protected_attr: "blahblah"}
end.to raise_error

但是 Rspec 说:预期的异常,但没有提出任何问题

而如果在规范文件中,我们删除期望块,如

post :create, account: {protected_attr: "blahblah"}

运行spec时会出现异常:

ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: protected_attr

rspec 的 raise_error 怎么没有捕捉到异常呢?

4

2 回答 2

3

The problem is that you're trying to get an exception on your post :create, account: {protected_attr: "blahblah"} but all this code does is return a http response.

You can't use expect {}.to raise_exception here.

To test the exception you shouldn't do it within the controller spec (I would do it on spec/models/account_spec.rb. Something like:

expect do
  described_class.create!(protected_attr: 'blahblah')
end.to raise_exception

On your controller you can just test for the response code to not be success:

post :create, account: {protected_attr: "blahblah"}

expect(response).to_not be_success
expect(response.status).to be(422) # you can be specific about the code you're expecting
于 2015-03-11T18:12:14.763 回答
0

这不能完全回答您的问题,但它可能会解决您的问题。您没有在控制器测试中对其进行测试。只需在模型规格中进行测试。这是 Rails 3.x 中模型的一个问题。在 Rails 4 中将使用不同的方法。

于 2013-05-15T09:04:31.723 回答