如何在 ActiveSupport::TestCase 中存根方法

How to stub a method in ActiveSupport::TestCase

RSpec 中,我可以像这样存根方法:

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

如何使用 ActiveSupport::TestCase 存根方法?

我有这样的测试。

class CompanyTest < ActiveSupport::TestCase
  test 'foobar' do
    company = companies(:base)
    #company.stubs(:foo).returns(300)
    assert_nil(company.calculate_bar)
  end
end

Minitest 的模拟功能有限,但我建议对这些类型的存根使用 mocha gem。

Mocha 的语法正是您在注释掉的行中的语法:

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

Minitest 附带一个开箱即用的 stub 方法,以防您不想使用外部工具:

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

增强@Farrukh 的回答:

如果你想验证传递的参数,比如allow(company).to receive(:foo).with(some_args).and_return(300),

您可以使用 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