AGirlThatCodes
AGirlThatCodes

Reputation: 585

Creating multiple factories to test ordering

I'm trying to test the order of a factory. (1) I need help on writing a test that tests if the factory ordering is correct. So I assume I would have to create the factory and then alter the results and then sort them.

Also, (2) I would like to know if there is a DRYer way to creating multiple items in the Factories.

spec/models/item_spec.rb

require 'rails_helper'

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

  let(:item) { FactoryGirl.create(:item) }
  let(:item2) { FactoryGirl.create(:item) }
  let(:item3) { FactoryGirl.create(:item) }

  it "should sort the items in order" do
    # tests order
  end
end

spec/factories/items.rb

FactoryGirl.define do
  factory :item, :class => 'Item' do
    name { Forgery::Name.name }
    sequence(:ordering)
  end
end

Upvotes: 0

Views: 1134

Answers (3)

Spasm
Spasm

Reputation: 805

# spec/model/item_spec.rb
require 'spec_helper'

describe Item do
  let(:items) { FactoryGirl.create_list(:item, 3) }

  it "should sort the items in order" do
    # tests order
  end      
end

Also does the same thing. Checkout the docs

Upvotes: 0

Jed Schneider
Jed Schneider

Reputation: 14671

at some point here, you are testing that FactoryGirl is working correctly. Assuming that ordering has some sorting mechanism, you could also test that the comparator is working properly:

expect(generate(:ordering) <=> generate(:ordering)).to eq(-1)
# because
expect(1 <=> 2).to eq(-1)

if its something akin to the email sequences in the readme, and your ordering is incorrect, its probably a bug in FactoryGirl.

Upvotes: 0

Pete
Pete

Reputation: 2246

In similar situations I've used Ruby's .times method (docs) to generate a set amount of Factory items and then map the objects into an array:

# spec/model/item_spec.rb
require 'spec_helper'

describe Item do

  let(:items) {3.times.map {FactoryGirl.create(:item)} } # An array of Items

  it "should sort the items in order" do
    # tests order
  end      
end 

Upvotes: 1

Related Questions