Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test for warnings using RSpec

Is it somehow possible to test warnings i Ruby 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
like image 515
Linus Oleander Avatar asked Mar 27 '11 12:03

Linus Oleander


1 Answers

warn is defined in Kernel, which is included in every object. If you weren't raising the warning during initialization, you could specify a warning like this:

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

Spec'ing a warning raised in the initialize method is quite more complex. If it must be done, you can swap in a fake IO object for $stderr and inspect it. Just be sure 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
like image 115
David Chelimsky Avatar answered Sep 28 '22 04:09

David Chelimsky