aquajach
aquajach

Reputation: 2578

Expect Rspec to raise exceptions in controller

I am trying to test on a controller if it raises errors when mass-assignment protected attributes are to be updated.

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

However Rspec says: expected Exception but nothing was raised

While if in spec file, we remove the expect block, like

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

There will be an exception when running the spec:

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

How come does rspec's raise_error not capture the exception?

Upvotes: 2

Views: 4711

Answers (2)

rikas
rikas

Reputation: 490

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

Upvotes: 4

Kamil Jopek
Kamil Jopek

Reputation: 705

This is not exactly answer for your question but it might solve your problem. You don't have test it in controller tests. Just test in in model specs. It is a concern of models in Rails 3.x. In Rails 4 will be used different approach.

Upvotes: 0

Related Questions