Rspec 3 并断言该值具有对象 ID



我正在使用 Rspec 3,我正在尝试编写一个测试,该测试正在测试由我的 rake db:seed 任务填充的数据库中的值

到目前为止,我已经想出了

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

现在这是抛出一个错误

  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">]

所以我可能以错误的方式看待这个问题,我想检查的是组件 ID 1 实际上具有"识字"的component_name值

如果有人能指出我正确的方向,我将不胜感激

谢谢

你可以执行以下操作:

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

所以我可能以错误的方式看待这个问题,我想检查的是组件 ID 1 实际上具有"识字"的component_name值

如果这确实是您想要的,只需执行以下操作:

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

您正在将 ActiveRelation 对象与哈希 ( {id: 1} ) 进行比较。比较 id,如下所示。

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

最新更新