Method: Object#mock!
- Defined in:
- lib/motion-spec/mock/mock.rb
#mock!(method, options = {}, &block) ⇒ Object
Create a mock method on an object. A mock object will place an expectation on behavior and cause a test failure if it’s not fulfilled.
Examples
my_string = "a wooden rabbit"
my_string.mock!(:retreat!, :return => "run away! run away!")
my_string.mock!(:question, :return => "what is the airspeed velocity of an unladen sparrow?")
# test/your_test.rb
my_string.retreat! # => "run away! run away!"
# If we let the test case end at this point, it fails with:
# Unmet expectation: #<Sparrow:1ee7> expected question
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/motion-spec/mock/mock.rb', line 17 def mock!(method, = {}, &block) MotionSpec::Mocks.add([self, method]) behavior = if block_given? lambda do |*args| fail ArgumentError if block.arity >= 0 && args.length != block.arity MotionSpec::Mocks.verify([self, method]) block.call(*args) end elsif ![:yield].nil? lambda do |*_args| MotionSpec::Mocks.verify([self, method]) yield([:yield]) end else lambda do |*_args| MotionSpec::Mocks.verify([self, method]) return [:return] end end method, &behavior end |