2009-08-22 77 views
0

我想模拟一个正在传递给另一个对象的对象,并且没有成功。有人能告诉我我做错了什么吗?rspec模拟问题

class Fetcher 
    def download 
    return 3 
    end 
end 

class Reports 
    def initialize(fetcher) 
    @fetcher = fetcher 
    end 
    def status 
    @fetcher.download 
    end 
end 


describe Reports do 
    before(:each) do 
    end 

    it "should get get status of 6" do 
    Fetcher.should_receive(:download).and_return(6) 
    f = Reports.new(Fetcher.new) 
    f.status.should == 6 
    end 
end 

该规范仍然报告状态返回3,不是我的意图6.

当然我在这里失去了一些东西。有什么想法吗?

回答

1

在测试中,我认为你正在试图做的是这样的(我认为)

it '...' do 
    some_fetcher = Fetcher.new 
    some_fetcher.should_receive(:download).and_return(6) 

    f = Reports.new(some_fetcher) 
    f.status.should == 6 
end 

当你说Fetcher.should_receive(:下载),你说的CLASS应该接收打电话'下载',而不是类的实体...

希望这有助于!如果不清楚,请告诉我!

+0

谢谢,就是这样。但是......两件事。 1.为什么Fetcher的实例不会继承对类的更改?如果我向Fetcher添加了一个新的方法,然后实例化它,它会有这种方法,不是吗? 2.我在rspec的Peepcode screencast上得到了上面的代码。原始代码是针对Rails模型的,如下所示: def mock_feed(zipcode,how_many = 1) xml = ... Weather.should_receive(:open).exactly(how_many).times。 (“http://weather.yahooapis.com/forecastrss?p=#{zipcode}”)。 and_return(xml) end 为什么他的类修改工作,而不是我的? – 2009-08-22 03:16:29

+0

对于#1,你可以做到这一点,但是如果不能保证在正确的时间实例化第二个类,那么很容易出现问题。您可能不想按照您所描述的方式定义新方法,而是尝试使用“instance_eval”。 所以,如果你想添加一个方法弗莱彻,你可以这样做: Fletcher.class_eval做 高清some_method ... 结束 结束 一些其他人比我能解释这更好的。这里有一些链接: http://bmorearty.wordpress.com/2009/01/09/fun-with-rubys-instance_eval-and-class_eval/ #2,我不能解决问题。你能再试一次吗? – btelles 2009-08-23 02:11:16

0

根据新的语法进行更新。

subject(:reports) { described_class.new(fetcher) } 
let(:fetcher}  { double("Fetcher") } 

describe "#status" do 
    it "gets status of 6" do 
    fetcher.stub(download: 6) 
    expect(reports.status).to == 6 
    end 
end