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

5
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
3个回答

6

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

3

Minitest提供了一些有限的模拟功能,但我建议使用mocha gem来进行这些存根(stubs)。

Mocha的语法与你在注释行中看到的完全相同:

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

1

加强@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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接