mercredi 24 mai 2017

FactoryGirl not finding instances in DB

When attempting to initialize data with FactoryGirl I am running into a problem with being able to access previous data I have created.

Say I have 3 different Models: Product, CartItem, and OrderItem. And these are the basic rules:

  • CartItem and OrderItem belong_to Product, and is required.
  • Product has a unique identifier 'name'.

My Factory files are set up like so:

Product

FactoryGirl.define do factory :product do name "A Product" end end

CartItem

FactoryGirl.define do factory :cart_item do association :product do Product.find_by("A Product") || FactoryGirl.create(:product) end end end

OrderItem

FactoryGirl.define do factory :order_item do association :product do Product.find_by("A Product") || FactoryGirl.create(:product) end end end

Now, within one test, I first create CartItem using this call FactoryGirl.create(:cart_item)

Everything runs fine. Because there is no Product, it creates a new one and then assigns it to CartItem.

Next, I then attempt to create OrderItem using this call FactoryGirl.create(:order_item)

This time when I run it, it fails with the error Validation failed, Name has already been taken

This fails when trying to create a new Product with the name "A Product", which was already created from the call to create CartItem.

However, this should never even attempt to create a new Product instance because I set the OrderItem's product using this Product.find_by("A Product") || FactoryGirl.create(:product) which should first attempt to find that product instance before creating a new one.

Any ideas as to why this is occurring?

Aucun commentaire:

Enregistrer un commentaire