0
votes

I'm trying to test to see if the items the array exist after I create the factory.

spec/models/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

spec/factories/things.rb

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

Below are the results that I received.

results

  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
Does it work? What's your question? Are you getting an exception? - Nick Veys
(delayed response) Thank you. Based on your suggestion, I was able to update it and have a response. Thanks again. - AGirlThatCodes

1 Answers

0
votes

You can't do it this way. You'll have to check each record individually like this

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

Or do something like this:

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

You can only use include to check if the array includes an element as a whole, like this:

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