How to stub a module method inside a controller with Mocha

2k views Asked by At

I have a Sinatra app like this:

my_module.rb

module MyModule
  def my_method
    "yay"
  end
end

app.rb

get "/my_module" do 
  puts my_method
end

I'm trying to stub my_method on a test with Minitest and mocha.

def test_my_method
  MyModule.stubs(:my_method).returns("stubbed")
  get "/my_module"
end

But this don't seems to work, because the original method is still called. Any thoughts on how to do this? Thanks!

1

There are 1 answers

0
Matheus Richard On BEST ANSWER

I've found out two different ways to achieve this.

1) Using stub any instance gem.

With this gem I could stub any instace of Sinatra::Application. So the solution looks like this:

def test_my_method
  Sinatra::Application.stub_any_instance(:my_method, "stubbed") do
    get "/my_module"
    # => stubbed
  end
end

2) Using mocha's any_instance.

This solution follows the same principle. Just using mochas methods.

def test_my_method
  Sinatra::Application.any_instance.stubs(:my_method).returns("stubbed")
  get "/my_module"
  # => stubbed
end