2013-02-20 63 views
1

我的测试用例低于:Rspec的存根方法调用记录

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 

我如何存根化方法要求直接从数据库中检索的记录?

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

回答

0

这里的问题是(如你所发现的)调用查找方法将创建一个新的实例Petition。为了解决这个问题,你可以存根查找方法本身,就回到你想要的对象:

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 

不幸的夫妇,任何你正在测试的实施规范。如果您使用其他方式获取请愿书,可能会中断。更具弹性的方法可能会使用工厂,并创建具有适当属性的请求。