theDrifter
theDrifter

Reputation: 1706

Rails FactoryGirl Sequences - Test created object

I use sequences like the following

 sequence (:role_id){|n| "10#{n}" }

Now when i create a factory with

 FactoryGirl.create :account, name: "name", phone:"1234", role_id: FactoryGirl.generate(:role_id)

How can i test for the generated role_id value?

 expect(account.role_id).to eq ?

Upvotes: 0

Views: 100

Answers (2)

muichkine
muichkine

Reputation: 2940

I'm not sure I follow how you use sequencing.

Traditional way is in your Factory

FactoryGirl.define do
  factory :account do
     name { "whatever" } 
     sequence(:role_id){ |i| "10#{i}"}
     phone{ "5555" }
  end
end

You can then generate accounts like so:

account = FactoryGirl.create :account, name: "name", phone:"1234"

it will override every passed parameter with what you provided.

You can also specify :role_id:

account = FactoryGirl.create :account, name: "name", phone:"1234", :role_id => "1015"

Now, you can test any value you wish. For instance with RSpec:

account = FactoryGirl.create :account, name: "name", phone:"1234"
expect(account.role_id).to eq "1001".

But there is no point since what you are testing here is FactoryGirl. And that has already been tested. :)

Upvotes: 1

Elena
Elena

Reputation: 157

You shouldn't do it. Sequences are used to generate unique random data. If you want to have a role association on your model, consider something like this in your factory:

FactoryGirl.define do
  factory :person do
    role

    sequence(:email) { |n| "email-#{n}@example.com" }
    phone SecureRandom.uuid
  end
 end

Upvotes: 1

Related Questions