mercredi 3 mai 2017

FactoryGirl: RecordInvalid with association length minimum validation on create

I have model Question that is has_many Answer. I require a question to have at least one answer and I'm testing with rspec

validates :answers, length: { minimum: 1 }

My factory:

FactoryGirl.define do
  factory :question do
    text "Enunciado de la pregunta"
    transient do
      multiple false
      custom_answer false
      answers_count 2
    end

    after(:create) do |q, ev|
      create_list(:answer, ev.answers_count, question: q)
    end
  end

  factory :answer do
    text "Enunciado de la respuesta"
    transient do
      custom false
    end
  end
end

But when I do create(:question) in the spec file it throws a RecordInvalid exception (create tries to save model, but associated answers are created after create).

Tried changing to after(:build) but it doesn't work as well.

How can I build the needed answers preserving the transient answers_count parameter without callbacks?

Aucun commentaire:

Enregistrer un commentaire