Rails RR单元测试:模拟ActiveRecord模型方法的问题



考虑以下类和方法:(这个类显然更完整,但为了这个线程…):

class Order < ActiveRecord::Base
  def check
    if (self.user.phone == "55555555") do
      self.a_certain_method
      return
    end
  end
  def a_certain_method
    # Real implementation goes here
  end
end

和下面的单元测试:

describe :do_route do
it "should call a_certain_method if user phone number matches 55555555" do
  # Create a user
  user = Factory(:user)
  # Set hard-coded phone number
  user.phone = "55555555"
  user.save!
  # Create an order made by the ordering user
  order = Factory(:order, :ordering_user => user)
  # Set expectation for a "a_certain_method" call
  mock(order).a_certain_method
  # Call the tested method
  order.check
end
end

由于某种原因,上面的测试产生了一个RR::Errors::TimesCalledError错误,它声称a_certain_method被调用了0次而不是1次…我一直在网上寻找解决方案,但没有运气。

我尝试在非activerecord类上构建类似的测试,测试没有产生错误。我已经使用调试器来检查它是否到达self.a_certain_method行,并且还尝试使用以下命令代替mock(order).a_certain_method:

  any_instance_of(Order) do |o|
    mock(o).a_certain_method
  end

有没有人知道如何解决这个问题,因为我有点绝望…

我弄清楚问题是什么,它失败了,因为这个数字已经在数据库中了。所以它没能保存硬编码用户。手机改变。

谢谢你的帮助:)

最新更新