【问题标题】:How to get instance_of to work with ActiveRecord objects in RoR?如何让 instance_of 与 RoR 中的 ActiveRecord 对象一起工作?
【发布时间】:2010-03-02 08:59:16
【问题描述】:

今天我在使用 RoR 对 AR 对象的调用存根时遇到了问题。我认为我可以按照以下方式做一些事情:

stub.instance_of(BankAccount).save_to_other_spot { true }

但是,当我尝试此方法时,它似乎根本没有存根该方法,它最终会运行我试图存根的原始方法。我使用调试器等确认了这一点。

所以我最终使用了以下方法:

stub.proxy(BankAccount).find(anything) do |account|
  stub(account).save_to_other_spot { true }
  account
end

这行得通。

我想知道我是否做错了什么?为什么 instance_of 不按我期望的方式工作?

我遇到的另一个问题是,在我的 RSpec 测试中,我似乎必须为每个请求设置我的模拟和存根。同样,这是正常的还是我做错了什么?

我的意思是我必须做类似的事情:

... mock and stub ...
get :show, :id => @id

... mock and stub ...
post :update, :id => id, :account => { ... params ... }

我以为我可以在顶部进行一次模拟和存根。

【问题讨论】:

    标签: ruby-on-rails ruby testing rspec integration-testing


    【解决方案1】:

    假设您正在运行 RSpec >2.5... 那么模拟/存根语法已得到改进,因此您现在可以使用以下定义。

    BankAccount.any_instance.stub(:save_to_other_spot) { true }
    

    请注意,您需要使用a latter version of RSpec。早期版本的 RSpec 不包括 any_instance 方法。看起来他们是从 Mocha 那里借来的,并将其实现到 RSpec 模拟中。

    如果您使用的是旧版本的 RSpec,那么我认为您正在做的事情是唯一的方法。只是我倾向于这样写:

    @bank_account = BankAccount.new
    BankAccount.stub(:find) { @bank_account }
    @bank_account.stub(:save_to_other_spot) { true }
    

    尽管我认为您的块方法看起来更干净。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-02
      • 1970-01-01
      • 2017-06-25
      • 2020-12-13
      • 2012-02-02
      • 2011-02-22
      相关资源
      最近更新 更多