4

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 2

3

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

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

1 Comment

Thank you, that works! Could you see my other question about RSpec if you have a chance? I appreciate it! The is the link.
0

I guess you are trying to test API response with JSON format. You could try json_spec gem with many other helpful features https://github.com/collectiveidea/json_spec

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.