How to stub a method in ActiveSupport::TestCase

耗尽温柔 提交于 2019-12-23 13:08:38

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/38867168/how-to-stub-a-method-in-activesupporttestcase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!