Created
November 3, 2014 14:56
-
-
Save ale7714/5b51c33cdf741756e554 to your computer and use it in GitHub Desktop.
Custom warn message expectation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rspec' | |
require 'stringio' | |
# Custom matcher to test message written when warn | |
# | |
# Example | |
# expect { subject.do_something }.to warn('Some error message') | |
# | |
# Source | |
# http://danielchangnyc.github.io/blog/2014/01/15/tdd2-RSpecMatchers/ | |
RSpec::Matchers.define :warn do |message| | |
match do |block| | |
output = get_stderr(&block) | |
output.include? message | |
end | |
# Get STDERR and return the string. | |
def get_stderr | |
original_stderr = $stderr | |
$stderr = StringIO.new | |
yield | |
@buffer = $stderr.string | |
ensure | |
$stderr = original_stderr | |
end | |
description do | |
%Q[warn #{message.inspect}] | |
end | |
def failure_message(to = 'to') | |
%Q[expected #{to} #{description} but got #{@buffer.inspect}] | |
end | |
failure_message_for_should do | |
failure_message 'to' | |
end | |
failure_message_for_should_not do | |
failure_message 'not to' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment