Joshua Ball
Joshua Ball

Reputation: 23740

rspec mock question

I am trying to Mock an object that is being passed into another object, and am having no success. Can someone show me what I am doing wrong?

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

The spec still reports status returning 3, not my intended 6.

Certainly I am missing something here. Any thoughts?

Upvotes: 0

Views: 340

Answers (2)

Pablo Cantero
Pablo Cantero

Reputation: 6357

An updated based on the new syntax.

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

Upvotes: 0

btelles
btelles

Reputation: 5420

In the test, what I think you're trying to do is this (I think)

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

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

when you say Fetcher.should_receive(:download), you're saying the CLASS should receive the call 'download', instead of INSTANCES of the class...

Hope this helps! If it's not clear, just let me know!

Upvotes: 1

Related Questions