5

In RSpec I could stub method like this:

allow(company).to receive(:foo){300}

How can I stub a method with ActiveSupport::TestCase?

I have a test like this.

class CompanyTest < ActiveSupport::TestCase
  test 'foobar' do
    company = companies(:base)
    #company.stubs(:foo).returns(300)
    assert_nil(company.calculate_bar)
  end
end
ironsand
  • 14,329
  • 17
  • 83
  • 176

3 Answers3

6

Minitest comes with a stub method out of the box, in case you don't wanna use external tools:

require 'minitest/mock'
class CompanyTest < ActiveSupport::TestCase
  test 'foobar' do
    company = companies(:base)
    Company.stub :foo, 300 do
      assert_nil(company.calculate_bar)
    end
  end
end
3

Minitest has some limited functionality for mocks, but I'd suggest using the mocha gem for these kinds of stubs.

The syntax for Mocha is exactly what you have on the commented out line:

class CompanyTest < ActiveSupport::TestCase
  test 'foobar' do
    company = companies(:base)
    company.stubs(:foo).returns(300)
    assert_nil(company.calculate_bar)
  end
end
Eugen Minciu
  • 121
  • 4
1

Enhancing @Farrukh answer:

If you want to verify the arguments passed, like allow(company).to receive(:foo).with(some_args).and_return(300),

You can use assert_called_with.

# requiring may not be needed, depending on ActiveSupport version
require "active_support/testing/method_call_assertions.rb"
include ActiveSupport::Testing::MethodCallAssertions  # so we can use `assert_called_with`
 
assert_called_with(company, :foo, some_args, returns: 300) do
  assert_nil(company.calculate_bar)
end
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Foton
  • 1,197
  • 13
  • 24