简体   繁体   中英

How to mock a method in a module in ruby?

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM