rspec来测试ruby方法是否返回一个数组

时间:2014-10-28 07:40:01

标签: ruby rspec

我有一个返回数组的方法。我需要使用rspec测试它。有没有我们可以测试的方法:

def get_ids
  ####returns array of ids
end

subject.get_ids.should be_array

result = subject.get_ids
result.should be an_instance_of(Array)

1 个答案:

答案 0 :(得分:15)

那么,取决于你究竟在寻找什么。

检查返回的值是否为数组(be_an_instance_of):

expect(subject.get_ids).to be_an_instance_of(Array)

或检查返回的值是否与预期数组(match_array)的内容匹配:

expect(subject.get_ids).to match_array(expected_array)

<强>更新

如Patrick的评论中所述,要检查数组的等效匹配,请使用eq

expect(subject.get_ids).to eq(expected_array)

对于数组使用equal的身份匹配:

expect(subject.get_ids).to equal(expected_array)