如果方法(例如#each)在没有给出块时返回枚举器,如何检查rspec?

时间:2017-11-16 15:12:06

标签: ruby rspec

我在my_each中定义了enumerable_methods.rb方法。它的作用与#each相同:当没有给出块时,它返回一个枚举器。在我的enumerable_methods_spec.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

我无法弄清楚如何解决它。

3 个答案:

答案 0 :(得分:1)

我会将测试分成两部分:

expect(array.my_each).to be_a(Enumerator)
expect(array.my_each.to_a).to eq(array)

答案 1 :(得分:1)

这么简单吗?

expect(array.my_each).to be_an Enumerator

实际的内容检查也很有用,如@ mudasobwa的回答所示。

答案 2 :(得分:0)

expect(array.my_each.inspect).to eql(array.to_enum(:my_each).inspect)