lost9123193
lost9123193

Reputation: 11030

How to test for object attributes using Rspec

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?

Upvotes: 0

Views: 2286

Answers (2)

max
max

Reputation: 101811

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
})

Upvotes: 1

t56k
t56k

Reputation: 6981

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.

Upvotes: 0

Related Questions