Skip to content

Instantly share code, notes, and snippets.

@maxjustus
Last active December 17, 2015 05:09
Show Gist options
  • Save maxjustus/5555613 to your computer and use it in GitHub Desktop.
Save maxjustus/5555613 to your computer and use it in GitHub Desktop.
safer stubs
module RSpec::Mocks::Methods
# Validates the method exists on the stub-ee before stubbing
def s_stub(message_or_hash, opts={}, &block)
if Hash === message_or_hash
message_or_hash.each {|message, value| s_stub(message).and_return value }
else
raise "#{message_or_hash} not defined on #{self.inspect}" unless self.respond_to?(message_or_hash.to_sym)
stub(message_or_hash.to_sym, opts, &block)
end
end
def s_should_receive(message, opts={}, &block)
raise "#{message} not defined on #{self.inspect}" unless self.respond_to?(message.to_sym)
should_receive(message, opts, &block)
end
end
class Cat
def meow
p "Moew!"
end
end
describe Cat do
it "woofs" do
c = Cat.new
c.s_stub(:woof => "woof") # throws error
c.woof
end
it "guffaws" do
c = Cat.new
c.s_should_receive(:guffaw).with(:loudly) { "guffaw" } # throws error
c.guffaw
end
it "meows" do
c = cat.new
c.s_should_receive(:meow) { "Meow" } # works
c.meow
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment