0

我正在使用这个工厂为我的测试创建测验:

  factory :quiz_with_two_choices_first_correct, :class => Quiz do |i|
    quiz_type Quiz.SINGLE_ANSWER_CHOICE
    weight 1

    i.after_create do |quiz|
      quiz.quiz_choices = [FactoryGirl.create(:quiz_choice, :body=>'Quiz Choice 1', :is_correct=>true, :position=>1),
                           FactoryGirl.create(:quiz_choice, :body=>'Quiz Choice 2', :is_correct=>false, :position=>2)]
    end
  end

在我的测验模型中,我有:

  after_create { |record|

    if !current_unit.nil? then
      if current_unit_type.eql? FinalExam.to_s then
        current_unit.total_weights=
            current_unit.total_weights+ record.weight
        current_unit.save
      end
    end

  }

但是当我尝试测试时,我收到了这个错误:

Failure/Error: quiz= FactoryGirl.create(:quiz_with_two_choices)
     NoMethodError:
       undefined method `after_create=' for #<Quiz:0xb50075c>

这是我的测试:

describe "When a final question is created" do

  it "can't be deleted if any student is enrolled to it" do
    quiz= FactoryGirl.create(:quiz_with_two_choices)
    final_question = FinalExamQuestion.create(:quiz_id=>quiz.id)
    quiz_count_before_try_to_destroy_quiz= Quiz.all.count
    quiz.destroy
    Quiz.all.count.should == quiz_count_before_try_to_destroy_quiz
  end
  it "can be deleted if there isn't any student enrolled to it" do
    quiz= FactoryGirl.create(:quiz_with_two_choices)
    quiz_count_before_try_to_destroy_quiz= Quiz.all.count
    quiz.destroy
    Quiz.all.count.should_not == quiz_count_before_try_to_destroy_quiz
  end
end

那么,有什么问题呢?

4

1 回答 1

1

问题在于您在工厂内分配了一个 after create 块:

i.after_create do |quiz|
      quiz.quiz_choices = [FactoryGirl.create(:quiz_choice, :body=>'Quiz Choice 1', :is_correct=>true, :position=>1),
                           FactoryGirl.create(:quiz_choice, :body=>'Quiz Choice 2', :is_correct=>false, :position=>2)]
    end

这试图运行quiz.after_create=,显然没有这样的方法用于测验实例。

作为一种解决方案,您可以尝试使用以下对工厂女孩有效的语法:

  after(:create) do |quiz|
    # Do your quiz stuff here
  end
于 2013-01-31T08:18:24.297 回答