Skip to content

Instantly share code, notes, and snippets.

@floehopper
Forked from benpickles/test.rb
Created January 30, 2011 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save floehopper/803021 to your computer and use it in GitHub Desktop.
Save floehopper/803021 to your computer and use it in GitHub Desktop.
require 'test/unit'
require 'rubygems'
require 'mocha'
class Foo
def self.say_hello_to(name)
Bar.hello(name)
end
end
class Bar
end
class TestFooWithStubbingInSetup < Test::Unit::TestCase
def setup
@test = states("test").starts_as("stubbing")
@hello = mock("said hello")
Bar.stubs(:hello).returns(@hello).when(@test.is("stubbing"))
end
def test_something
Bar.expects(:hello).with("zab").when(@test.is("expecting"))
@test.become("expecting")
Foo.say_hello_to("baz")
end
def test_something_else
assert_equal @hello, Foo.say_hello_to("bob")
end
# Lots of other tests so it's convenient to stub Bar.hello in the setup...
end
class TestFooWithoutStubbingInSetup < Test::Unit::TestCase
def setup
@hello = mock("said hello")
end
def test_something
Bar.expects(:hello).with("zab")
Foo.say_hello_to("baz")
end
def test_something_else
Bar.stubs(:hello).returns(@hello)
assert_equal @hello, Foo.say_hello_to("bob")
end
end
@floehopper
Copy link
Author

Test output is now as follows :-

  1) Failure:
test_something(TestFooWithStubbingInSetup)
    [test.rb:7:in `say_hello_to'
     test.rb:24:in `test_something']:
unexpected invocation: Bar.hello('baz')
unsatisfied expectations:
- expected exactly once, not yet invoked: Bar.hello('zab'); when test is 'expecting'
satisfied expectations:
- allowed any number of times, not yet invoked: Bar.hello(any_parameters); when test is 'stubbing'
states:
- test is 'expecting'

  2) Failure:
test_something(TestFooWithoutStubbingInSetup)
    [test.rb:7:in `say_hello_to'
     test.rb:41:in `test_something']:
unexpected invocation: Bar.hello('baz')
unsatisfied expectations:
- expected exactly once, not yet invoked: Bar.hello('zab')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment