2

I'm fairly new to Ruby/Ruby on Rails and having trouble stubbing out a method via mocha in an existing codebase.

I've simplified the code down to a MWE where this breaks.

Here is test_helper.rb:

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)

require "rails/test_help"


class ActiveSupport::TestCase

end


class Minitest::Test
  def before_setup

  end
end

And here is the test:

require 'test_helper'
require 'mocha/minitest'

class MyTest < ActionMailer::TestCase

  describe "some test" do
    it "should stub" do
      My::Class.stubs(:bar).returns("foo")
      puts My::Class.bar
    end
  end

end

This results in the following error when I run the test:

Mocha::NotInitializedError: Mocha methods cannot be used outside the context of a test

However, when I redefine my test_helper.rb as follows:

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)

require "rails/test_help"


class ActiveSupport::TestCase

end


# class Minitest::Test
#   def before_setup
#
#   end
# end

The test passes (and "foo" is printed as expected).

Why does the class Minitest::Test...end in test_helper.rb cause the first error? I can't remove that code from the actual codebase, so how can I modify it to work with mocha?

Ruby version: 2.4.1

Rails version: 4.2.8

Mocha version: 1.5.0

Vega
  • 27,856
  • 27
  • 95
  • 103
LateCoder
  • 2,163
  • 4
  • 25
  • 44

1 Answers1

2

Adding a call to super in the patched method before_setup in test_helper.rb works:

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)

require "rails/test_help"


class ActiveSupport::TestCase

end


class Minitest::Test
  def before_setup
      # do something
      super
  end
end

This call to super allows the before_setup of Mocha::Integration::MiniTest to be called, which is necessary for proper initialization.

LateCoder
  • 2,163
  • 4
  • 25
  • 44