rspec模拟问题

时间:2009-08-22 00:35:36

标签: ruby mocking 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。

当然,我在这里遗漏了一些东西。有什么想法吗?

2 个答案:

答案 0 :(得分: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(:download)时,你说CLASS应该接收“下载”的呼叫,而不是类的INSTANCES ......

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

答案 1 :(得分: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