我正在使用 Mocha 和 MiniTest 使用 TDD 学习 Ruby。我有一个类有一个公共方法和许多私有方法,所以我的测试要测试的唯一方法是公共方法。
这个公共方法做一些处理并创建一个发送给另一个对象的数组:
def generate_pairs()
# prepare things
pairs = calculate_pairs()
OutputGenerator.write_to_file(path, pairs)
end
伟大的。为了测试它,我想模拟该OutputGenerator.write_to_file(path, pairs)
方法并验证参数。我可以成功实施的第一个测试:
def test_find_pair_for_participant_empty_participant
available_participants = []
OutputGenerator.expects(:write_to_file).once.with('pairs.csv', [])
InputParser.stubs(:parse).once.returns(available_participants)
pair = @pairGenerator.generate_pairs
end
现在我想和一对参与者一起测试。我正在尝试这个
def test_find_pair_for_participant_only_one_pair
participant = Object.new
participant.stubs(:name).returns("Participant")
participant.stubs(:dept).returns("D1")
participant_one = Object.new
participant_one.stubs(:name).returns("P2")
participant_one.stubs(:dept).returns("D2")
available_participants = [participant_one]
OutputGenerator.expects(:write_to_file).once.with('pairs.csv', equals([Pair.new(participant, participant_one)])) # here it fails, of course
InputParser.stubs(:parse).once.returns(available_participants)
@obj.stubs(:get_random_participant).returns(participant)
pair = @obj.generate_pairs
end
问题是 equals 只会匹配 obj 引用,而不是内容。
有什么方法可以验证数组的内容吗?验证数组中元素的数量也非常有用。
ps:如果代码不符合ruby标准,我很抱歉,我正在做这个项目来学习语言。