Factory Girl - creating a factory with active record validations

70 Views Asked by At

So I have a factory to create an item. Which can contain one or more line_items.

describe Item do
  let(:user) { create :user }
  let(:currency) { create :currency }
  subject(:item) { create :item, currency: currency, create_user: user, update_user: user }

It fails when creating the item with an active record validation:

ActiveRecord::RecordInvalid: Validation failed: You have not entered any data and cannot save a blank form., You have not entered any data and cannot save a blank form.

Is this because a line_item is not being created when an item is created?

In my factory, whenever I create a line_item, I create an item:

FactoryGirl.define do
  factory :line_item do
    item
    create_user factory: :user
    update_user factory: :user
  end
end
1

There are 1 best solutions below

0
On

Make Sure that your models are validated by your model validations in your Factory. Please can you paste your models. Try the code below. It is not tested so you have to doctor it based on your model.

FactoryGirl.define do
    factory :user do
        sequence(:username) { |n| "foo#{n}"}
        password "password"
        email {"#{username}@example.com"}
    end

    factory :item do
        name "item1"
        user
    end

    factory :line_item do
        name "line_item1"
        item
    end
end