I'm building a very small gem to read an image data format and return the image either as a boring ruby array, or a nice narray, depending on a) if an narray has been requested and b) 开发者_运维百科if the narray gem is available and required. My design is that if someone wants to use narray they can, but they have to require it explicitly before-hand. When reading the image data, I check to see if narray is defined (has been required), and simply adds a warning to a msg instance variable for later printing/logging.
I'd like to include a test for this (I'm using rspec2 and mocha for mocking) but I'm a little new to actually using rspec. I'd like to do something like:
it "should return an narray if requested" do
obj = NRead.new(@string, :bin => true, :narray => true)
obj.image_narray.should_not be_nil
end
it "should add an NArray Install message and not set the image_narray if NArray was not available" do
Object.stubs(:defined?).with(:NArray).returns(:false)
obj = NRead.new(@string, :bin => true, :narray => true)
obj.msg.should_not be_empty
obj.msg.grep(/Please gem install narray/).empty.should be_false
obj.image_narray.should be_nil
obj.image_ruby_array.size.should == @fixture_image_length
end
...but I must be missing the point of using stubs, because this stubbing isn't changing the behavior of defined?. Regardless of the stub, defined? returns the "real" value (i.e. if I uncomment the require in the code, defined? is false and my warning is successfully added).
Is this not even worth testing? Is there a better way to do this? Any thoughts would be appreciated. Thanks,
defined? is not a method of Object. This is why your stub is not working. It is a ruby operator. I am not certain how to stub out an operator. This is definitely worth testing as it is important to the functioning of your code.
To test this you can pop the gem out of $" array in ruby which has the kernel.load info and call in before block:
Object.send(:remove_const, :NArray)
Then in after block you can rerequire it. It is a bit hackish perhaps there is a better way.
精彩评论