【问题标题】:Rails RR UnitTesting: Problems with mocking an ActiveRecord model methodRails RR UnitTesting:模拟 ActiveRecord 模型方法的问题
【发布时间】:2011-12-13 10:18:24
【问题描述】:

考虑以下类和方法:(这个类显然要完整得多,但是为了这个线程......):

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 次...我一直在网上搜索解决方案,但没有成功。

我尝试在非活动记录类上构建类似的测试,并且测试没有产生错误。 我已经使用调试器检查它是否到达self.a_certain_method 行,并且还尝试使用以下而不是mock(order).a_certain_method

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

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

【问题讨论】:

  • 我试图重现您的问题,但没有成功。您可以为用户和订单添加Gemfile 的代码和工厂的定义吗?还可以尝试将测试中的用户初始化更改为user = Factory(:user, :name =&gt; "55555555"),它会通过吗?
  • 我找出了问题所在,因为该号码已经在数据库中,所以它失败了。所以它无法保存硬编码的 user.phone 更改。不过感谢您的帮助:)
  • 您能否将此评论作为答案发布并接受它,以便 StackOverflow 不会将您的问题视为未回答。你的问题stackoverflow.com/q/8464376/158689 也回答了吗?谢谢!
  • 我的意思是接受你自己的答案绝对没问题。

标签: ruby-on-rails unit-testing rspec rr


【解决方案1】:

我发现问题出在哪里,因为号码已经在数据库中,所以它失败了。所以它无法保存硬编码的 user.phone 更改。

感谢您的帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多