FactoryGirl:RecordInvalid,创建

时间:2017-05-03 10:18:50

标签: ruby-on-rails testing rspec

我的模型Questionhas_many Answer。我要求一个问题至少有一个答案,我正在使用rspec

进行测试
validates :answers, length: { minimum: 1 }

我的工厂:

FactoryGirl.define do
  factory :question do
    text "Enunciado de la pregunta"
    transient do
      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"
  end
end

但是当我在spec文件中执行create(:question)时会抛出RecordInvalid异常(创建尝试保存模型,但创建后会创建相关的答案)。

尝试更改为after(:build),但效果不佳。

如何构建所需的答案,在没有回调的情况下保留瞬态answers_count参数?

2 个答案:

答案 0 :(得分:1)

如您所知,在保存问题之前,您需要创建关联。

我认为你可能想做这样的事情:

FactoryGirl.define do
  factory :question do
    ...
    answers { [association(:answer, answers_count: 2 )] }
  end
end

或者build_list方法可能会有所帮助:

after(:build) do |q, ev|
  build_list(:answer, ev.answers_count, question: q)
end

我能够使用after(:build)。有关after(:build)及其回调顺序,请参阅docs

我使用此设置在mongo中工作:

#spec/models/question_spec.rb
describe Question do
  let!( :question ){create :question}

  it 'should work', :focus do
    expect( question ).to be_valid
    puts question.inspect
    puts question.answers.inspect
  end
end

#spec/factories/questions.rb
FactoryGirl.define do
  factory :question do
    text "Enunciado de la pregunta"
    transient do
      answers_count 2
    end

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

  factory :answer do
    text "Enunciado de la respuesta"
  end
end

#models/question.rb
class Question
  include Mongoid::Document
  include Mongoid::Attributes::Dynamic

  field :text,      type:String

  has_many :answers
  validates_presence_of :answers
end

#models/answer.rb
class Answer
  include Mongoid::Document
  include Mongoid::Attributes::Dynamic

  field :text,      type:String

  belongs_to :question
end

我的测试结果如下:

Run options: include {:focus=>true}
#<Question _id: 590a20ef8a681843088580bb, text: "Enunciado de la pregunta">
[#<Answer _id: 590a20ef8a681843088580ba, text: "Enunciado de la respuesta", question_id: BSON::ObjectId('590a20ef8a681843088580bb')>, #<Answer _id: 590a20ef8a681843088580bc, text: "Enunciado de la respuesta", question_id: BSON::ObjectId('590a20ef8a681843088580bb')>]
.

Finished in 0.16217 seconds (files took 2.87 seconds to load)
1 example, 0 failures

答案 1 :(得分:1)

经过多次尝试,它开始使用:

after(:build) do |q, ev|
  q.answers = build_list(:answer, ev.answers_count, question: q)
end

为什么呢?如果有人知道,那么解释它会很棒。