如何在Rspec测试中跳过after_create回调?

时间:2016-01-11 01:33:57

标签: ruby-on-rails rspec

我有一个SaleQualifier模型has_many Answers。我尝试设置一个基本的Rspec测试,以确保Answer始终使用以下内容引用其父SaleQualifier

  it 'is invalid without a sale_qualifier' do
   answer.sale_qualifier_id = nil
   expect(answer).to_not be_valid
 end

我的Answer模型有一个after_save回调,可通过answer_type及其关联的SaleQualifier查找Question。它看起来像这样:

class Answer < ActiveRecord::Base
 validates :answer_text, presence: true
 belongs_to :sale_qualifier
 validates :sale_qualifier_id, presence: true
 validate :check_answer_text_type
 after_save :update_sale_qualifier

 TYPE_REGEX = {
    'Integer' => /^[-+]?\d+$/,
    'Boolean' => /^(true|false)$/
 }

 def check_answer_text_type
    question = Question.find_by_id(self.sale_qualifier.question_id)
    answer_type = question.answer_type
    if answer_type == 'Datetime'
        if !answer_text.is_a?(Date)
            self.errors.add(:answer_type, 'must be a valid date')
        end
    elsif answer_type == 'Integer' || answer_type == 'Boolean'  
        unless answer_text.match(TYPE_REGEX[answer_type])
            self.errors.add(:answer_type, 'invalid format')
        end
    else
        return true
    end
 end

 def update_sale_qualifier
    sale_qualifier.update_next_question
    sale_qualifier.save
 end
end

正如您所看到的,Answer模型使用question = Question.find_by_id(self.sale_qualifier.question_id)通过SaleQualifier模型找到问题 - 当我将代码validates :sale_qualifier_id, presence: true添加到我的Answer模型时,这可行(答案不再有效)但它也会破坏check_answer_text_type方法,因为对self的调用不再有效。

这会产生NoMethodError for nil:NilClass,这是预期的。

在这种情况下,有没有办法可以跳过after_save验证?无论如何,我在代码的其他部分进行了测试,我试图在这里实现的是证明答案不会被允许在我的数据库中浮动而不与SaleQualifier相关联。

1 个答案:

答案 0 :(得分:1)

一个非常简单的方法是存根update_sale_qualifier,所以你会检查它是否确实被调用,但代码不会被执行所以你的测试应该没问题:

expect(answer).to receive(:update_sale_qualifier)

您可以查看RSpec doc on this

相关问题