0

I'm trying to test the reponse.json output from a show method in a controller:

describe "#show" do
 let!(:animal){create(:animal, name:"Cat"}
 let(:params) {{id: animal.id}}

 subject {get :show, params: params}

 context "when animal campaign exists" do
  it "should have the expected keys" do
    subject

    response_json = JSON.parse(response.body)
    expected_keys = [
      "animal_name",
      "id", 
      ]
      expect(response_json).to include(*expected_keys)

The expected object that is output is not being compared to the expected_keys:

  expected {"animal_name" => "Cat, "animal_id" => 6999} 
  Diff:
       @@ -1,23 +1,23 @@
       -["animal_name",
       - "animal_id"]

How can I check for the expected_keys?

1
  • 2
    try expect(response_json.keys).to include(*expected_keys) Commented Feb 12, 2020 at 0:58

2 Answers 2

1

While you could use:

expect(response_json.keys).to include [""animal_name", "id"]

The failure message is going to be very cryptic as it tells us nothing about what you are actually trying to test.

Slightly better is:

expect(response_json).to have_key "animal_name"
expect(response_json).to have_key "animal_id"

But you can actually test the correctness of the JSON against the model:

expect(response_json).to include({
  "animal_name" => "Cat"
  "animal_id" => animal.id
})
Sign up to request clarification or add additional context in comments.

Comments

0

This feels like a weird test to write, but you could just map out the keys from response.body.

I don't know what your controller looks like, but I'd guess there's some relational thing going on which prepends animal_ to your response.

Wouldn't a better test simply be something like this?

describe 'GET show' do
  it 'will show an animal campaign' do
    get :show, params: { id: animal.id }
    expect(response.parsed_body).to include 'animal_name'
  end
end

Judging from your output that should pass, although I'm not quite sure what exactly you're testing for.

Comments

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.