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

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.

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.

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?

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

Related

Yielding self to rspec test inside each loop yields last known state

I'm writing some rspec tests for some web-pages. One of the pages contains several links that I want to test as a group. So my test looks something like this
require 'spec_helper'
t = Page.new
t.test do |t|
describe 'a thing' do
it 'should not be last' do
t.title
end
end
end
So when I call t.title I am actually calling that on the the following Page object being yielded (by itself) down below.
and my Page object looks like this
class Page
attr_accessor :driver
def initialize()
#driver = Watir::Browser.new :phantomjs
#home = ''
#driver.goto(#home)
end
def visit(url)
#driver.goto(url)
end
def title
#driver.title
end
def test
#subpages.each do |page|
visit(page)
yield self
end
end
end
So now when I run rspec, what ends up happening is the test will run as many times as I expect it to, however it runs each time it yields the object in the state it's in during the final iteration of visit. So it's not really testing the pages the way I want it to, it's testing the last page in the list.
Am I incorrectly using yield or self here? It seems pretty straightforward: pass the test as a block to the Page object's test method and have it run the test on itself.
Any tips? I'd like to be able to keep all the tests clean, and all the logic in the page object, but this is hindering me from doing so.
Within the scope of a given file, RSpec examples/tests don't get executed until they all have been defined. You're iterating through the page defining all these examples, but RSpec is collecting and not executing them until the iteration is complete, at which time the value of t remains unchanged and corresponds to the final state of the page.

Using RSpec to test user input with gets

I'm new to Unit Testing using RSpec and Ruby and I have a question on how to test if my code is using the gets method, but without prompting for user input.
Here is the code I'm trying to test. Nothing crazy here, just a simple one liner.
my_file.rb
My_name = gets
Here's my spec.
require 'stringio'
def capture_name
$stdin.gets.chomp
end
describe 'capture_name' do
before do
$stdin = StringIO.new("John Doe\n")
end
after do
$stdin = STDIN
end
it "should be 'John Doe'" do
expect(capture_name).to be == 'John Doe'
require_relative 'my_file.rb'
end
end
Now this spec works, but when I run the code it prompts for user input. I don't want it to do that. I want to simply test if the gets method is being called and possibly mock the user input. Not to sure how to achieve this in RSpec. In Python I would utilize unittest.mock is there a similar method in RSpec?
Thanks in advance!
Here's how you could stub gets with your return value.
require 'rspec'
RSpec.describe do
describe 'capture_name' do
it 'returns foo as input' do
allow($stdin).to receive(:gets).and_return('foo')
name = $stdin.gets
expect(name).to eq('food')
end
end
end
Failures:
1) should eq "food"
Failure/Error: expect(name).to eq('food')
expected: "food"
got: "foo"
(compared using ==)
To test if something is being called (such as a function) you can use expect($stdin).to receive(:gets).with('foo') to ensure it is being called (once) with the right args. The expectation line in this scenario has to go before name = $stdin.gets.

Embed RSpec test in a Ruby class

I often build little single-purpose Ruby scripts like this:
#!/usr/bin/env ruby
class Widget
def end_data
DATA.read
end
def render_data source_data
source_data.upcase
end
end
w = Widget.new
puts w.render_data(w.end_data)
__END__
data set to work on.
I'd like to include RSpec tests directly inside the file while I'm working on it. Something like this (which doesn't work but illustrates what I'm trying to do):
#!/usr/bin/env ruby
class Widget
def end_data
DATA.read
end
def render_data source_data
source_data.upcase
end
def self_test
# This doesn't work but shows what I'm trying to
# accomplish. The goal is to have RSpec run these type
# of test when self_test is called.
describe "Widget" do
it "should render data properly" do
#w = Widget.new
expect(#w.render_data('test string')).to eq 'TEST STRING'
end
end
end
end
w = Widget.new
w.self_test
__END__
data set to work on.
I understand this is not the normal way to work with RSpec and isn't appropriate in most cases. That said, there are times when it would be nice. So, I'd like to know, is it possible?
There are two things. First off rspec by default won't pollute the global namespace with methods like describe and so on. The second thing is that you need to tell rspec to run the specs after they've been declared.
If you change your self_test method to be
RSpec.describe "Widget" do
it "should render data properly" do
#w = Widget.new
expect(#w.render_data('test string')).to eq 'TEST STRING'
end
end
RSpec::Core::Runner.invoke
(having of course done require 'rspec' then that will run your specs).
The invoke methods exits the process after running the specs. If you don't want to do that, or need more control over where output goes etc. you might want to drop down to the run method which allows you to control these things.

Detect Rspec test failure on after each method

I am trying to run an RSpec test, and I want to detect if the test failed in the after method. I have something like this right now:
after(:each) do
cc = ConnectController.new()
cc.update(<TEST-SERVER-CONTROLLER>, <TC-RESULT-ID>, result?)
end
As you can see, the result? function is what I need to replace, to detect if the test fails or not, and to also get information about the test that failed.
In addition to Daniel's answer, in Rspec3 the example method was deleted (see here for more info).
You will have to do something like this:
after(:each) do |example|
if example.exception
# ...
end
end
EDIT: this answer is only valid for RSpec 2. for RSpec 3 see geekazoid's answer.
The after each block runs in the context of class which exposes example and you can detect failures by checking the exception method on example thusly:
after(:each) do
if example.exception != nil
# Failure only code goes here
end
end
I was looking for how to check if success for all examples in a group in a after(:context) / after(:all) block. Here's what I came up with:
after(:all) do |example_group|
all_groups = example_group.class.descendants
failed_examples = all_groups.map(&:examples).flatten.select(&:exception)
if failed_examples.empty?
# runs only if there are no failures
do('something')
end
end

RSpec: how do I write a test that expects certain output but doesn't care about the method?

I'm trying to get my head around test-driven design, specifically RSpec. But I'm having trouble with some of the examples from The RSpec Book.
In the book, we test for output on $STDOUT like this:
output = double('output')
game = Game.new
output.should_receive(:puts).with('Welcome to Codebreaker!')
game.start()
Well, that works after a fashion. But why on earth should I care if the Game object uses the puts() method? If I change it to print(), should it really break the test? And, more importantly, isn't this against the one of the principals of TDD - that I should be testing what the method does (the design) rather than how it does it (the implementation)?
Is there some way I can write a test that just tests what ends up on $STDOUT, without looking at what method puts it there?
Create a display class with the ability to write the status out.
You production code will make use of this display object so you are free to change how you write to STDOUT. There will be just one place for this logic while your tests rely on the abstraction.
For example:
output = stub('output')
game = Game.new(output)
output.should_receive(:display).with('Welcome to Codebreaker!')
game.start()
While your production code will have something such as
class Output
def display(message)
# puts or whatever internally used here. You only need to change this here.
end
end
I'd make this test pass by doing the following:
def start
#output.display('Welcome to Codebreaker!')
end
Here the production code doesn't care how the output is displayed. It could be any form of display now the abstraction is in place.
All of the above theory is language agnostic, and works a treat. You still mock out things you don't own such as third party code, but you are still testing you are performing the job at hand via your abstraction.
take a look at this post. Nick raised questions about the same example, and a very interesting conversation follows in the comments. Hope you find it helpful.
Capture $stdout and test against that instead of trying to mock the various methods that might output to stdout. After all, you want to test stdout and not some convoluted method for mimicking it.
expect { some_code }.to match_stdout( 'some string' )
Which uses a custom Matcher (rspec 2)
RSpec::Matchers.define :match_stdout do |check|
#capture = nil
match do |block|
begin
stdout_saved = $stdout
$stdout = StringIO.new
block.call
ensure
#capture = $stdout
$stdout = stdout_saved
end
#capture.string.match check
end
failure_message_for_should do
"expected to #{description}"
end
failure_message_for_should_not do
"expected not to #{description}"
end
description do
"match [#{check}] on stdout [#{#capture.string}]"
end
end
RSpec 3 has changed the Matcher API slightly.
failure_message_for_should is now failure_message
failure_message_for_should_not is now failure_message_when_negated
supports_block_expectations? has been added to make errors clearer for blocks.
See Charles' answer for the complete rspec3 solution.
The way I'd test it is with a StringIO object. It acts like a file, but doesn't touch the filesystem. Apologies for the Test::Unit syntax - feel free to edit to RSpec syntax.
require "stringio"
output_file = StringIO.new
game = Game.new(output_file)
game.start
output_text = output_file.string
expected_text = "Welcome to Codebreaker!"
failure_message = "Doesn't include welcome message"
assert output_text.include?(expected_text), failure_message
I came across this blog post which helped me solve this issue:
Mocking standard output in rspec.
He sets up before/after blocks, and I ended up doing them inside the actual rspec itself, for some reason I couldn't get it to work from my spec_helper.rb as recommended.
Hope it helps!
An updated version of Matt's answer for RSpec 3.0:
RSpec::Matchers.define :match_stdout do |check|
#capture = nil
match do |block|
begin
stdout_saved = $stdout
$stdout = StringIO.new
block.call
ensure
#capture = $stdout
$stdout = stdout_saved
end
#capture.string.match check
end
failure_message do
"expected to #{description}"
end
failure_message_when_negated do
"expected not to #{description}"
end
description do
"match [#{check}] on stdout [#{#capture.string}]"
end
def supports_block_expectations?
true
end
end

Resources