Created
October 15, 2013 05:07
-
-
Save JonathonMA/6986762 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MiniStub | |
def initialize *args | |
unless args.first.is_a? Hash | |
@name = args.shift | |
end | |
@stubbed = args.first || {} | |
end | |
def inspect | |
"#<MiniStub(#{@name})>" | |
end | |
def stub! name, value = nil, &block | |
if value | |
@stubbed[name] = value | |
elsif block | |
@stubbed[name] = block | |
else | |
@stubbed[name] = nil | |
end | |
end | |
def respond_to? method | |
@stubbed.has_key?(method) || super | |
end | |
def method_missing method, *args | |
if @stubbed.has_key? method | |
stub = @stubbed[method] | |
if stub.respond_to? :call | |
stub.call *args | |
else | |
stub | |
end | |
else | |
super | |
end | |
end | |
module TestHelper | |
def stub *args | |
MiniStub.new *args | |
end | |
end | |
end | |
require 'minitest/unit' | |
require 'minitest/autorun' | |
require 'minitest/pride' | |
class MiniStubTest < MiniTest::Unit::TestCase | |
def test_works | |
a_stub = stub | |
assert a_stub | |
end | |
def test_naming | |
a_stub = stub :foo | |
assert_match /foo/, a_stub.inspect | |
end | |
def test_query_methods | |
a_stub = stub foo: "bar" | |
assert_equal "bar", a_stub.foo | |
end | |
def test_query_callable | |
a_stub = stub foo: -> { "bar" } | |
assert_equal "bar", a_stub.foo | |
end | |
def test_method_with_parameters | |
a_stub = stub foo: "bar" | |
assert_equal "bar", a_stub.foo("baz") | |
end | |
def test_method_with_parameters | |
a_stub = stub foo: ->(a) { a.upcase } | |
assert_equal "BAZ", a_stub.foo("baz") | |
end | |
def test_respond_to_acts_properly | |
a_stub = stub foo: "bar" | |
assert a_stub.respond_to? :foo | |
end | |
def test_can_build_stubs_afterwards | |
a_stub = stub | |
a_stub.stub!(:foo) { "foo" } | |
assert_equal "foo", a_stub.foo | |
end | |
def test_stub_bang_works_with_values | |
a_stub = stub | |
a_stub.stub! :foo, "bar" | |
assert_equal "bar", a_stub.foo | |
end | |
def test_stub_bang_no_arguments_is_cool | |
a_stub = stub | |
a_stub.stub! :foo | |
a_stub.foo | |
assert true # no real assert, just making sure we don't raise | |
end | |
include MiniStub::TestHelper | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice :)