来自另一个助手的

时间:2016-11-07 19:06:13

标签: ruby-on-rails rspec

我有一个铁路助手 - FirstHelper:

module FirstHelper
  def a_method_from_first_helper(args)
    # do something with args and return a value
  end
end

我打电话给第二个帮手SecondHelper:

module ProjectHelper
  def a_method_from_second_helper(project)
    a_method_from_first_helper(args)
  end
end

a_method_from_first_helper方法在其规范中经过全面测试。在我的second_helper_spec.rb中,我希望能够从a_method_from_first_helper中删除FirstHelper方法,以便我可以监视它并检查是否使用正确的参数调用它。

我无法解决如何做到这一点 - 我已经尝试过各种各样的方法 - 这是我目前的尝试

require 'rails_helper'
include FirstHelper

RSpec.describe SecondHelper, :type => :helper do
  describe '#a_method_from_second_helper' do
    it 'calls a_method_from_first_helper with the correct arguments' do
      spy = instance_double('a_method_from_first_helper')
      allow(helper).to receive('a_method_from_first_helper').and_return(spy)
      a_method_from_second_helper
      expect(spy).to have_received(correct_arguments)
    end
  end
end

但是这并没有覆盖FirstHelper

中的方法

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

实际上它比这更容易,因为期望和间谍可以一步设置:

require 'rails_helper'

RSpec.describe SecondHelper, :type => :helper do
  SecondHelper.module_eval do
    extend FirstHelper
  end

  describe '#a_method_from_second_helper' do
    it 'calls a_method_from_first_helper with the correct arguments' do
      expected_args = nil # the expected args come here
      expect(helper).to receive(:a_method_from_first_helper).with(expected_args)
      helper.a_method_from_second_helper
    end
  end
end

修改

我刚刚意识到你的助手不包括FirstHelper,请参阅示例中的module_eval