5

How can I use stub method in setup? I only found the stub with block like this:

class FooTest < ActiveSupport::TestCase
  test 'for_something' do
    Foo.stub :some_method, 3 do
      #assert_equal
    end
  end  
end

But I want to stub for all tests. How can I stub it?

ironsand
  • 14,329
  • 17
  • 83
  • 176

2 Answers2

7

You can achieve that by overriding #run method in your test case:

class FooTest < ActiveSupport::TestCase
  def run
    Foo.stub :some_method, 3 do
      super
    end
  end

  test 'for_something' do
    #assert_equal
  end  
end

It's a common way to introduce the code that needs to be executed "around" every test case.

lest
  • 7,780
  • 2
  • 24
  • 22
2

I think this already answered here - https://stackoverflow.com/a/39081919/3102718

With gem mocha you can stub methods in setup or in test, e.g.:

require 'active_support'
require 'minitest/autorun'
require 'mocha/mini_test'

module Foo
end

class FooTest < ActiveSupport::TestCase
  setup do
    Foo.stubs(:some_method).returns(300)
  end

  test 'for_something' do
    assert Foo.some_method == 300
  end
end
Community
  • 1
  • 1
Oleksandr Avoiants
  • 1,889
  • 17
  • 24