Skip to content

Instantly share code, notes, and snippets.

@akasper
Created January 12, 2012 19:57
Show Gist options
  • Save akasper/1602743 to your computer and use it in GitHub Desktop.
Save akasper/1602743 to your computer and use it in GitHub Desktop.
RSpec "double"
class Store
def foo
Storage.store "abc", "bbc"
end
# def bar
# storage = Storage.new
# storage.some_instance_method "cnn"
# end
# I recommend that you instead set it up like this:
def bar
storage.some_instance_method "cnn"
end
# This way, you can stub #storage in specs, and it
# becomes a modifyable integration point in the future.
def storage
@storage ||= Storage.new
end
end
# In spec
describe "#foo" do
# You need a subject so that you can actually call the methods.
# If you don't specify the subject, the subject just becomes
# described_class.new
# (In this case, Store.new)
it "should call Storage.store" do
# If you set #should_receive, you don't need to stub!
# Storage.stub(:store)
Storage.should_receive(:store).with("abc", "bbc")
# Make sure you actually call the method. #should_receive isn't
# evaluated until after the example has run to completion.
subject.foo
end
end
describe "#bar" do
it "should call storage.some_instance_method" do
# Doesn't matter what you name it. The name is just a helper
# that you can use for better feedback when the spec fails.
storage = double("storage")
# Is the above the right way to test "Storage" and "storage"?
# Not exactly. What you're trying to specify is that "the storage
# attribute can just be a double. What you really want is something more
# like this:
subject.stub(:storage).and_return(storage)
storage.should_receive(:some_instance_method).with("cnn")
# Again, make sure to actually call the method
subject.bar
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment