主体(类)在方法中返回自己。

问题描述 投票:0回答:1

我在做一门课程的练习,我要写代码让下面的测试通过。

  it 'returns itself when exiting a journey' do
    expect(subject.finish(station)).to eq(subject)
  end

我已经写好了

    class Journey
      ...
      def finish(station)
        Journey
      end
      ...
    end

我得到了错误。

expected: #<Journey:0x00007fd90091e7c8>
            got: Journey

       (compared using ==)

       Diff:
       @@ -1,2 +1,2 @@
       -#<Journey:0x00007fd90091e7c8>
       +Journey

我写的时候觉得有点太简单了 但我不知道还能怎么写。如果有任何帮助,将非常感谢,谢谢!

class testing rspec
1个回答
1
投票

你正在返回一个类

      def finish(station)
        Journey
      end

但你需要返回一个实例。

      def finish(station)
        Journey.new
      end

但这还不够好,因为你需要返回与该方法被调用的对象相同的实例"

      def finish(station)
        self
      end
© www.soinside.com 2019 - 2024. All rights reserved.