Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stub a module method inside a controller with Mocha

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!

like image 423
Matheus Richard Avatar asked Oct 28 '25 04:10

Matheus Richard


1 Answers

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
like image 178
Matheus Richard Avatar answered Oct 29 '25 19:10

Matheus Richard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!