soulnafein
soulnafein

Reputation: 1068

How to verify that "puts" has been called with a certain message?

I'm trying to make this test fail :)

it "should display the question" do
  @ui.should_receive(:puts).with("What's your name?").once
  @ui.ask_question("What's your name?")
end

At the moment it passes even if I don't call puts in my function.

Upvotes: 3

Views: 275

Answers (3)

Avdi
Avdi

Reputation: 18418

Given the code:

require 'rubygems'
require 'spec'

class UI
  def ask_question(q)
  end
end

describe UI do
  before do
    @ui = UI.new
  end

  it "should display the question" do
    @ui.should_receive(:puts).with("Whats your name?").once
    @ui.ask_question("Whats your name?")
  end
end

I get the failure:

F

1) Spec::Mocks::MockExpectationError in 'UI should display the question'
#<UI:0xb738effc> expected :puts with ("Whats your name?") once, but received it 0 times /home/avdi/tmp/puts_spec.rb:15:

Finished in 0.002575 seconds

1 example, 1 failure

What version of RSpec are you using?

Upvotes: 1

Justin Blake
Justin Blake

Reputation: 261

Basically, @ui should call .puts on an object that probably defaults to $stdout. Then in your tests, you can replace $stdout with a StringIO object that you can set expectations on. This has the added benefit of making your @ui object more flexible.

Upvotes: 3

Michael Kohl
Michael Kohl

Reputation: 66837

You can try stringio or ZenTest, the following ruby-talk thread has more info.

Upvotes: 0

Related Questions