【问题标题】:Rspec stub method calls on records记录上的 Rspec 存根方法调用
【发布时间】:2013-02-20 12:20:29
【问题描述】:

我的测试用例如下:

    petition1 = Petition.create
    petition2 = Petition.create

    petition1.should_receive(:test_method).with(7).and_return(50.0)
    petition2.should_receive(:test_method).with(7).and_return(25.0)

    petition1.test_method(7) # => 50.0
    Petition.first.test_method(7) # => 0.0

    petition2.test_method(7) # => 25.0
    Petition.last.test_method(7) # => 0.0

如何为直接从数据库检索的记录存根方法调用?

我正在对单元测试中的记录进行迭代,我需要对某些记录进行方法调用以返回特定响应。

【问题讨论】:

    标签: ruby unit-testing testing rspec tdd


    【解决方案1】:

    这里的问题是(正如您所发现的)调用 find 方法将创建Petition 的新实例。为了解决这个问题,您可以自己存根 find 方法并返回您想要的对象:

    let(:petition1) { Petition.create }
    let(:petition2) { Petition.create }
    
    it "does what I want" do
      Petition.stub(:first) { petition1 }
      Petition.stub(:last) { petition2 }
      petition1.should_receive(:test_method).with(7).and_return(50.0)
      petition2.should_receive(:test_method).with(7).and_return(25.0)
      # test code
    end
    

    不幸的是,这将规范与您正在测试的任何方法的实现结合在一起。如果您使用其他方式获取请愿书,这可能会中断。一种更具弹性的方法可能会改用工厂,并创建具有适当属性的请愿书。

    【讨论】:

      猜你喜欢
      • 2020-08-05
      • 1970-01-01
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多