测试FactoryGirl结果

时间:2014-11-14 04:25:51

标签: ruby-on-rails ruby testing rspec factory-bot

我正在尝试测试在创建工厂后是否存在数组中的项目。

规格/模型/ thing_spec.rb

require 'rails_helper'

RSpec.describe Thing, :type => :model do

  let(:thing) { Array.new(3) {FactoryGirl.create(:thing) } }

  it "should sort the items in order" do
    expect(thing).to include(ordering:1, ordering:2, ordering:3)
  end
end

规格/工厂/ things.rb

FactoryGirl.define do
  factory :thing, :class => 'Thing' do
    name "item_name"
    sequence(:ordering)
  end
end

以下是我收到的结果。

结果

  1) Things should be sorted in order
     Failure/Error: expect(thing).to include(ordering:1, ordering:2, ordering:3)
   expected [#<Thing id: 1, name: "item_name", create_date: "2014-11-07 04:18:17", modified_date: "2014-11-14 04:18:17", ordering: 1>, #<Thing id: 2, name: "item_name", create_date: "2014-11-07 04:18:17", modified_date: "2014-11-14 04:18:17", ordering: 2>, #<Thing id: 3, name: "item_name", create_date: "2014-11-07 04:18:17", modified_date: "2014-11-14 04:18:17", ordering: 3>] to include {:ordering => 2}
       Diff:
       @@ -1,2 +1,19 @@
       -[{:ordering=>2}]
       +[#<Thing:0x007fb96217cc30
       +  id: 1,
       +  name: "item_name",
       +  create_date: Fri, 07 Nov 2014 04:18:17 UTC +00:00,
       +  modified_date: Fri, 14 Nov 2014 04:18:17 UTC +00:00,
       +  ordering: 1>,
       + #<Thing:0x007fb9621cfca0
       +  id: 2,
       +  name: "item_name",
       +  create_date: Fri, 07 Nov 2014 04:18:17 UTC +00:00,
       +  modified_date: Fri, 14 Nov 2014 04:18:17 UTC +00:00,
       +  ordering: 2>,
       + #<Thing:0x007fb96221eda0
       +  id: 3,
       +  name: "item_name",
       +  create_date: Fri, 07 Nov 2014 04:18:17 UTC +00:00,
       +  modified_date: Fri, 14 Nov 2014 04:18:17 UTC +00:00,
       +  ordering: 3>]

1 个答案:

答案 0 :(得分:0)

你不能这样做。您必须像这样单独检查每条记录

it "should sort the items in order" do
  expect(thing[0].ordering).to eq(1)
  expect(thing[1].ordering).to eq(2)
  expect(thing[2].ordering).to eq(3)
end

或者做这样的事情:

it "should sort the items in order" do
  expect(thing.map(&:ordering)).to eq([1, 2, 3])
end

您只能使用include来检查数组是否包含整个元素,如下所示:

expect(thing).to include(thing[0])