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

时间:2016-08-10 07:44:55

标签: ruby-on-rails testcase

x=B() x.address='1973' x.save() 我可以使用这样的存根方法:

RSpec

如何使用allow(company).to receive(:foo){300} 存根方法?

我有这样的测试。

ActiveSupport::TestCase

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

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

答案 2 :(得分: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