I have the following factories set up
factory :request do
instructions "I want cheap food."
allergens "Nothing special"
after(:create) do |request, factory|
FactoryGirl.create(:request, customer: factory.requested_by)
FactoryGirl.create(:request, suburb: factory.suburb)
trait :with_customer do
factory :customer do
address "321 Sample Street"
trait :with_request do
after(:create) do |request, evaluator|
create_list(request, evaluator.request_count, customer: customer)
trait :with_diet do
diet_info factory: :diet_info
trait :with_suburb do
it "returns active request assuming there is one" do
cus = create(:customer)
re = create(:request, requested_by: cus)
# this fails. expected 1, got 2
expect(cus.requests.first.id).to eq 1
expect(re.id).to eq (1)
expect(cus.has_active_request?).to be true
# this fails as well
expected: #<Request id: 1, customer_id: nil, suburb_id: nil, serves: 1, instructions: "I want cheap food.", all...othing special", active: true, created_at: "2016-08-15 11:33:05", updated_at: "2016-08-15 11:33:05">
got: #<Request id: 2, customer_id: 1, suburb_id: nil, serves: 1, instructions: "I want cheap food.", aller...othing special", active: true, created_at: "2016-08-15 11:33:05", updated_at: "2016-08-15 11:33:05">
(compared using ==)
When you call your
:request factory with
requested_by:, the factory definition creates one
after(:create) creates a second (attached to the
Customer you provided), and the factory returns the first. So the
Customer you provided is attached to the second
Request (ID 2), and the
Request that was returned is the first request (ID 1).
To fix it, don't create the request in the second callback, just associate the
Customer with it:
after(:create) do |request, factory| if factory.requested_by request.update_attributes! customer_id: factory.requested_by.id end if factory.suburb request.update_attributes! suburb_id: factory.suburb.id end end
P.S.: I think you want those traits inside the
factory do ... end blocks. Doesn't matter for the question you asked, though, since you didn't use the traits anywhere.