4

How can one test if a certain action raises an ActionController::ParameterMissing exception?

For example:

it "raises an exception" do
  post :create, {}
  expect(response).to raise ActionController::ParameterMissing
end

The above does not seem to work, it will fail the test with the ActionController::ParameterMissing exception.

1 Answer 1

21

Use the expect block syntax using the raise_error matcher:

it "raises an exception" do
  expect{ post(:create, {}) }.to raise_error ActionController::ParameterMissing
end

The reason that your code doesn't work is that post(:create, {}) raises the exception. This happens before the expect(response).to ... code gets executes. Since the #post message is not in a begin...end block, the raised exception is passed up to RSpec failing the test.

Sign up to request clarification or add additional context in comments.

3 Comments

Great! Can you explain why it works with an expect block but not with the code in the question?
The exception is raised as part of the call to post, not as part of the call to response
Key thing here to note is that the brackets for except have changed from ( ) to { }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.