Joseph Mate's Blog

Mocking Modules with Mocha

Posted in Uncategorized by Joseph on January 31, 2010

I could not find any examples on mocking modules with mocha. It’s probably because it’s so easy! It’s just like mocking an instance of a class.

the_module.rb :

module TheModule
    def the_module_function
        return "the real value"

test.rb :

require "test/unit"
require "mocha"
require "the_module"
include TheModule

class TheModuleTest < Test::Unit::TestCase
    # replace 'the real value' with 'the mocked value'"
    def test_it
        assert TheModule.the_module_function == "the real value"

        TheModule.stubs(:the_module_function).returns("the mocked value")

        assert TheModule.the_module_function == "the mocked value"

Running the tests:

jmate@CalculatorJozef:~/everything/workspaces$ ruby test.rb
Loaded suite test
Finished in 0.00096 seconds.

1 tests, 2 assertions, 0 failures, 0 errors


2 Responses

Subscribe to comments with RSS.

  1. […] Mocking Modules with Mocha […]

  2. Joseph’s Midterm Report « UCOSP said, on March 1, 2010 at 1:00 am

    […] reminds me of mocking JUnit tests in Java [2] […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: