Reputation: 15093
I have number_module.rb
with content:
def power2(x)
x * x
end
and test case tc_number.rb
:
require_relative('number_module')
require "test/unit"
require 'mocha/test_unit'
class TestSimpleNumber < Test::Unit::TestCase
def test_simple
assert_equal(4, power2(2) ) # how to mock power2 to return 3?
end
end
in order to practice mocking i want to mock power2 in the test case to return 3
instead of powering by 2
how can I do that?
Upvotes: 1
Views: 559
Reputation: 54223
From the documentation, it looks like you can just use expects(:method_name).returns(result)
:
def power2(x)
x * x
end
require "test/unit"
require 'mocha/test_unit'
class TestSimpleNumber < Test::Unit::TestCase
def test_simple
expects(:power2).returns(3)
assert_equal(4, power2(2) )
end
end
The test fails as expected :
Loaded suite mocha
Started
F
=============================================================================================================================================================
Failure: test_simple(TestSimpleNumber)
mocha.rb:10:in `test_simple'
7: class TestSimpleNumber < Test::Unit::TestCase
8: def test_simple
9: expects(:power2).returns(3)
=> 10: assert_equal(4, power2(2) ) # how to mock power2 to return 3?
11: end
12: end
<4> expected but was
<3>
Upvotes: 5