我在做测试时找不到after_create

时间:2013-01-31 05:27:35

标签: ruby-on-rails-3.1 ruby-on-rails-3.2 rspec2 factory-bot

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

  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

那么,可能出现什么问题?

1 个答案:

答案 0 :(得分: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

这会尝试运行quiz.after_create=,显然测试实例没有这样的方法。

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

  after(:create) do |quiz|
    # Do your quiz stuff here
  end