RSpec:如何测试是否:使用正确数量的参数调用new

时间:2017-04-30 10:17:24

标签: rspec

我想测试我的班级初始化方法是否需要两个参数。我有以下内容:

class Game
end
...
require 'game'

describe Game do
  describe '#initialize' do
    it 'requires two players' do
      expect(Game).to respond_to(:new).with(2).arguments
    end
  end
end

由于某种原因上面的代码通过了,即使尝试使用2个参数初始化pry中的Game也会引发ArgumentError我期望的结果。如何正确编写上述测试?

1 个答案:

答案 0 :(得分:1)

我就是这样做的

require 'game'

describe Game do
  let(:player1) { Player.new(name: 'Player 1') }
  let(:player2) { Player.new(name: 'Player 2') }

  describe '#initialize' do
    context 'raises ArgumentError when' do
      let(:player3) { Player.new(name: 'Player 3') }

      it "is not called with exactly 2 players" do
        expect { Game.new(player1) }.to raise_error(ArgumentError)
        expect { Game.new(player1, player2, player3) }.to raise_error(ArgumentError)

        expect { Game.new(player1, player2) }.not_to raise_error
      end  
    end
  end
end

你明显需要班主任

class Player
  attr_reader :name

  def initialize(name:)
    @name = name
  end
end