[rspec-devel] [ rspec-Bugs-12845 ] Typo when using instance variables in specs leads to setting expectations on the nil object
noreply at rubyforge.org
noreply at rubyforge.org
Mon Aug 6 07:20:29 EDT 2007
Bugs item #12845, was opened at 2007-08-06 11:04
You can respond by visiting:
http://rubyforge.org/tracker/?func=detail&atid=3149&aid=12845&group_id=797
Category: mock module
Group: None
Status: Open
Resolution: None
Priority: 3
Submitted By: Ashley Moran (ashley_moran)
Assigned to: Nobody (None)
Summary: Typo when using instance variables in specs leads to setting expectations on the nil object
Initial Comment:
Just spent ages bashing my head against a wall on this, wondering why my spec was failing. Basically summed up in this example (not the shortest but similar to my code):
class Computer
attr_reader :power_indicator
def initialize(power_indicator)
@power_indicator = power_indicator
end
def turn_off
power_indicator.dim
end
end
describe Computer, "created with a PowerIndicator" do
before(:each) do
@power_indicator = mock("PowerIndicator")
@computer = Computer.new(@power_indicator)
end
it "should dim the power indicator when sent :turn_off" do
@power_indciator.should_receive(:dim)
@computer.turn_off
end
end
Basically I don't see a reason why you would ever set an expectation on "nil", so I wondered, would the following be better behaviour?
describe NilClass do
it "should raise an exception when sent :should_receive" do
lambda { nil.should_receive(:some_message) }.should raise_error(StandardError)
end
end
A bit like the way when you do "nil.id" in ActiveRecord you get the warning about calling nil.id in case you meant nil.object_id. WDYT?
----------------------------------------------------------------------
Comment By: Scott Taylor (smtlaissezfaire)
Date: 2007-08-06 11:20
Message:
Should this spec raise an error:
describe "NilClass"
it "should have an instance which is equal to nil" do
nil.should == nil
end
end
or how about this (in the case that method_one returns nil):
describe "method_one" do
it "should return the same value as method_two" do
method_one.should == method_two
end
end
It is in an interesting idea, although raising an error probably isn't. Maybe a warning.
Luckily for you (and all of us), this is easy enough to do in Ruby:
module Kernel
alias_method :__old_should, :should
def should(*args, &blk)
if self.class == NilClass
raise RuntimeError, "this is a nil!!"
else
__old_should(*args, &blk)
end
end
end
----------------------------------------------------------------------
You can respond by visiting:
http://rubyforge.org/tracker/?func=detail&atid=3149&aid=12845&group_id=797
More information about the rspec-devel
mailing list