Rspec - Compare two json values

Viewed 2118

I got a response from render json: { success: 'Success' }, I met a problem when I want to test if the response received the content like this. My unit test is:

    let(:success) do
      {
        success: "Success"
      }
    end

    it 'responds with json containing the success message' do
        expect(JSON.parse(response.body)).to eq(success)
    end

I got a failure from my test, which is:

expected: {:success=>"Success"}
got:      {"success"=>"Success"}

I tried to add double quote to success:'Success' so that it changed to 'success':'Success' but still have the same problem. I have two questions, the first is why there's a colon before the success, and the second is how could I remove it?

2 Answers

JSON.parse will have string-y keys by default.

my_hash = JSON.parse(response.body)
p my_hash.keys.first.class # String

If you want it to symbolize the keys,

my_hash = JSON.parse(response.body, symbolize_names: true)
p my_hash.keys.first.class # Symbol

Note: the option is called symbolize_names and not symbolize_keys.

Remember that a symbol is not a string:

p :success == 'success' # false

Related