Rspec 3 and asserting that value has object id

214 Views Asked by At

I am using Rspec 3 and I am trying to write a test that is testing values in the db populated by my rake db:seed task

So far I have come up with

describe "Component Data" do
  it 'Should have its values in the db' do
    expect(Component.where(component_name: 'Literacy')).to eq(id: 1)
  end
end

Now this is throwing an error

  Failure/Error: expect(Component.where(component_name: 'Literacy')).to eq(id: 1)

   expected: {:id=>1}
        got: #<ActiveRecord::Relation [#<Component id: 1, component_name: "Literacy", created_at: "2014-12-17 16:33:57", updated_at: "2014-12-17 16:33:57">]>

   (compared using ==)

   Diff:
   @@ -1,2 +1,2 @@
   -:id => 1,
   +[#<Component id: 1, component_name: "Literacy", created_at: "2014-12-17 16:33:57", updated_at: "2014-12-17 16:33:57">]

So i am probably looking at this in the wrong way, what I want to check for is that the Component Id of 1 actually has the component_name value of 'Literacy'

If anyone could point me in the right direction i would be grateful

Thanks

3

There are 3 best solutions below

1
On BEST ANSWER

You can do as :

describe "Component Data" do
  it 'Should have its values in the db' do
    expect(Component.find_by(component_name: 'Literacy').id).to eq(1)
  end
end
1
On

You are comparing an ActiveRelation object with a Hash ({id: 1}). Compare the id, like below.

expect(Component.where(component_name: 'Literacy').first.id).to eq(1)
0
On

So i am probably looking at this in the wrong way, what I want to check for is that the Component Id of 1 actually has the component_name value of 'Literacy'

If this is truly what you want, just do this:

expect(Component.find(1).component_name).to eql('Literacy')