Ruby 当没有给出块时,如何使用rspec检查方法(例如#each)是否返回枚举数?
我在Ruby 当没有给出块时,如何使用rspec检查方法(例如#each)是否返回枚举数?,ruby,rspec,Ruby,Rspec,我在enumerable\u methods.rb中定义了my\u each方法。它的工作原理与#each相同:当没有给定块时,它返回一个枚举数。在我的可枚举方法\u规范rb中: describe Enumerable do let(:array) {[1,2,3,4]} let(:answer) {[]} describe "#my_each" do ... context "when no block is given" do it "return
enumerable\u methods.rb
中定义了my\u each
方法。它的工作原理与#each
相同:当没有给定块时,它返回一个枚举数。在我的可枚举方法\u规范rb
中:
describe Enumerable do
let(:array) {[1,2,3,4]}
let(:answer) {[]}
describe "#my_each" do
...
context "when no block is given" do
it "returns an Enumerator" do
expect(array.my_each).to eql(array.to_enum(:my_each))
end
end
end
end
我在终端中遇到了这个错误:
Failures:
1) Enumerable#my_each when no block is given returns an Enumerator
Failure/Error: expect(array.my_each).to eql(array.to_enum(:my_each))
expected: #<Enumerator: [1, 2, 3, 4]:my_each>
got: #<Enumerator: [1, 2, 3, 4]:my_each>
(compared using eql?)
Diff:
# ./enumerable_methods_spec.rb:23:in `block (4 levels) in <top (required)>'
Finished in 0.02475 seconds (files took 0.12087 seconds to load)
2 examples, 1 failure
故障:
1) Enumerable#my_每个在未给定块时返回一个枚举数
失败/错误:预期(array.my_each).to eql(array.to_enum(:my_each))
预期:#
得到:#
(使用eql进行比较?)
差异:
#./可枚举方法规范rb:23:in“块(4级)in”
在0.02475秒内完成(加载文件需要0.12087秒)
2例,1例失败
我不知道如何修复它。我会将测试分为两部分:
expect(array.my_each).to be_a(Enumerator)
expect(array.my_each.to_a).to eq(array)
这么简单
expect(array.my_each).to be_an Enumerator
如@mudasobwa的回答所示,实际的内容检查也会很有用。
expect(array.my_each.inspect)。to eql(array.to_enum(:my_each.inspect)
如果my_each
返回,比如说,一个反向的枚举数,那么问题是“如何检查它会返回一个枚举数?”:)所以我回答了。但是,答案的第二部分在实际测试中也很有用。