如果模拟测试实例内部的方法,如何避免使用allow_any_instance_of

时间:2019-01-16 21:26:47

标签: rspec mocking ruby-on-rails-5

我想测试一个新对象的initialize,在此初始化中,调用了我需要模拟的方法(此方法要求用户输入名称...典型情况)

  class Setup
    attr_reader :player
    def initialize
      @player = new_player(cli_input('the name'))
    end

    private

    def cli_input('the name') # <<-- need to mock
      $stdin.gets.chomp.strip   
    end

    def new_player(name)
      Player.new(name)
    end
  end

setup_spec.rb

RSpec.describe Battleship::Setup do
  describe 'initialize' do

    it 'creates a player assigned to a instance variable' do
      allow_any_instance_of(Setup).to receive(:cli_input).with('the name').and_return('John')
      setup = Battleship::Setup.new
      expect(setup.player.name).to eq('John')
    end
  end
end

这可行,但是使用allow_any_instance_of

如何在没有它的情况下对其进行测试 allow_any_instance_of ,因为我已阅读过不应使用的

非常感谢

1 个答案:

答案 0 :(得分:0)

如果要使用在初始化函数内部调用私有方法,我怀疑除了allow_any_instance_of之外没有其他方法。将字符串文字the name放在方法定义中是错误的语法。

但是,您可以重构代码以使用重复测试来简化测试。

下面的代码演示了我的想法:

setup.rb

class Player
  attr_reader :name
  def initialize(name)
    @name = name
  end
end

class Setup
  class Client
    def cli_input
      $stdin.gets.chomp.strip
    end
  end

  attr_reader :player

  def initialize(client)
    @client = client
    @player = new_player(cli_input)
  end

  private

  def cli_input
    @client.cli_input
  end

  def new_player(name)
    Player.new(name)
  end
end

setup_spec.rb

RSpec.describe Setup do
  describe 'initialize' do

    it 'creates a player assigned to a instance variable' do
      client = Setup::Client.new
      allow(client).to receive(:cli_input).and_return("John")
      setup = Setup.new(client)
      expect(setup.player.name).to eq('John')
    end
  end
end