Verifying alerts using RSpec

Is it possible to somehow check for Ruby warnings using RSpec?

Like this:

class MyClass def initialize warn "Something is wrong" end end it "should warn" do MyClass.new.should warn("Something is wrong") end 
+7
ruby warnings testing rspec
Mar 27 '11 at 12:24
source share
3 answers

warn defined in Kernel , which is included in every object. If you did not raise a warning during initialization, you can specify a warning similar to this:

 obj = SomeClass.new obj.should_receive(:warn).with("Some Message") obj.method_that_warns 

The speculation of the warning raised in the initialize method is quite complex. If you need to do this, you can change the fake IO to the $stderr object and check it. Just remember to restore it after the example.

 class MyClass def initialize warn "Something is wrong" end end describe MyClass do before do @orig_stderr = $stderr $stderr = StringIO.new end it "warns on initialization" do MyClass.new $stderr.rewind $stderr.string.chomp.should eq("Something is wrong") end after do $stderr = @orig_stderr end end 
+15
Mar 27 2018-11-23T00:
source share

There is a nice article with custom wait that solves exactly your problem: http://greyblake.com/blog/2012/12/14/custom-expectations-with-rspec/

Therefore, he would like to:

 expect { MyClass.new }.to write("Something is wrong").to(:error) 

The basics of this article, you can create your own expectation to use it as follows:

 expect { MyClass.new }.to warn("Something is wrong") 
+4
Nov 21 '13 at 14:33
source share

This is my solution, I define a custom has_warn layout

 require 'rspec' require 'stringio' module CustomMatchers class HasWarn def initialize(expected) @expected = expected end def matches?(given_proc) original_stderr = $stderr $stderr = StringIO.new given_proc.call @buffer = $stderr.string.strip @expected.include? @buffer.strip ensure $stderr = original_stderr end def supports_block_expectations? true end def failure_message_generator(to) %Q[expected #{to} get message:\n#{@expected.inspect}\nbut got:\n#{@buffer.inspect}] end def failure_message failure_message_generator 'to' end def failure_message_when_negated failure_message_generator 'not to' end end def has_warn(msg) HasWarn.new(msg) end end 

Now you can use this function as shown below: Enable CustomMatchers:

 expect{ MyClass.new }.to has_warn("warning messages") 
0
Nov 03 '14 at 8:46
source share



All Articles