Rails / RSpec factory girl testing with invalid model produces strange behaviour

720 Views Asked by At

I am testing my rails controller with rspec and factory_girl

My actions returns error messages in json format with 412 status in case of invalid attributes

format.json{render json: user.errors.messages, status: 412}

like this

When I am trying to test the functionality

let(:invalid_attributes){
    FactoryGirl.attributes_for(:user,password: "password")
}
it "returns error if invalid attributes" do
  post :create,{user: invalid_attributes},valid_session
  expect(response).to have_status(412)
end

I get this error

 Failure/Error: expect(response).to have_status(412)
       expected #<ActionController::TestResponse:0x00000006f4cc10> to respond to `has_status?`

If i try to test like this

it "returns error if invalid attributes" do
    user = FactoryGirl.build(:user,invalid_attributes)
    post :create,{user: invalid_attributes},valid_session
    expect(response.body).to eq(user.errors.messages.to_json)
end

I get this error

 Failure/Error: expect(response.body).to eq(user.errors.messages.to_json)

       expected: "{}"
            got: "{\"password_confirmation\":[\"doesn't match Password\",\"doesn't match Password\"],\"password\":[\"Password must contain 1 Uppercase alphabet 1 lowercase alphabet 1 digit and minimum 8 charecters\"]}"

What is the problem?Thank you in advance

1

There are 1 best solutions below

4
On BEST ANSWER

You can test the response status like this:

expect(response.status).to eq(412)

And the JSON response with:

expect(response.body).to eq "{\"password_confirmation\":[\"doesn't match Password\",\"doesn't match Password\"],\"password\":[\"Password must contain 1 Uppercase alphabet 1 lowercase alphabet 1 digit and minimum 8 charecters\"]}"