Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stub a method in ActiveSupport::TestCase

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
like image 992
ironsand Avatar asked Aug 10 '16 07:08

ironsand


2 Answers

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
like image 50
Farrukh Abdulkadyrov Avatar answered Oct 01 '22 22:10

Farrukh Abdulkadyrov


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
like image 20
Eugen Minciu Avatar answered Oct 01 '22 22:10

Eugen Minciu