Search code examples
ruby-on-railsrspechttp-status-codeshuman-readable

How to use HTTP status code symbols in RSpec?


I use HTTP status code symbols in code in a controller such as:

render json: {
    auth_token: user.authentication_token, 
    user: user
  }, 
  status: :created

or

render json: {
    errors: ["Missing parameter."]
  }, 
  success: false, 
  status: :unprocessable_entity

In the code of my request spec I also would like to use the symbols:

post user_session_path, email: @user.email, password: @user.password
expect(last_response.status).to eq(201)

...

expect(last_response.status).to eq(422)

However each test where I use the symbols instead of integers fails:

Failure/Error: expect(last_response.status).to eq(:created)

  expected: :created
       got: 201

  (compared using ==)

Here is the latest list of HTTP status code symbols in Rack.


Solution

  • On the one hand, response is built with methods like:

    • success?

    • redirect?

    • unprocessable?

    • full list do: response.methods.grep(/\?/)

    On the other hand, Rspec predicates transforms every foo? method to a be_foo matcher.

    Not sure you can have the 201 this way unfortunately, but creating a custom matcher is quite easy.

    Note Rails test only rely on a few statuses.