简体   繁体   中英

Rails has many association with validation and factory girl

Consider a rails project with models User , List and Item .

list.rb

has_many :items
#check if the list has at least one item during save
validate :must_have_one_item_at_least

For this I have a factory like this:

factory :ordered_list_unpublished, traits: :ordered do
  transient do
    items_count 5
  end
  after(:build) do |list, evaluator|
    create_list(:item, evaluator.items_count, user: list.user, list: list)
  end
end

But the validation keeps failing when I do create(:ordered_list_unpublished) because of Validation failed: Items count is zero. Atleast one item must be present. Validation failed: Items count is zero. Atleast one item must be present.

You are calling create which will try and save the item into your database once it is created. The after :build callback will be run AFTER the create is finished, therefore it is trying to save into your database before it has added the items that would allow it to pass validation.

Instead of create try

build(:ordered_list_unpublished)

and you should be able to proceed as this will not attempt to save the model out.

Probably need to think about if you really require validation for the number of items to be greater than one as there may be situations where you want to create it first and add items later.

Another consideration, when you validate, you can specify to only validate on the first create, or to ignore the first create and then only validate when you are are updating:

validates :email, uniqueness: true, on: :create
validates :email, uniqueness: true, on: :update

This change to the factory made it work:

factory :ordered_list_unpublished, traits: [:ordered, :published] do
  transient do
    items_count 5
  end

  before(:create) do |list, evaluator|
    list.items << build_list(:item, evaluator.items_count, user: list.user, list: list)
  end
end

Thanks to this answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM