【问题标题】:Ruby rspec error for pushing into an array用于推入数组的 Ruby rspec 错误
【发布时间】:2020-05-14 12:28:02
【问题描述】:

我正在尝试通过将项目从另一个类推入数组的测试。 方法如下。

require_relative 'message'

class Test

  attr_reader :message

  def initialize(message = Message.new)
    @message = message
  end

  def push(hello)
    @message.array << hello
  end
end

另一个类中的空数组。

class Message

  attr_reader :array 

  def initialize
    @array = []
  end
end

还有我的测试。

require 'test'

describe Test do

  let(:message) { double(array: [])}

  describe '#push' do
    it 'pushes an item into an array from the message class' do
      subject.push("hello")
      expect(message.array).to eq ["hello"]
    end
  end
end

当前出现错误

expected: ["hello"]
     got: []

       (compared using ==)

我做错了什么?方法本身简单有效,为什么我的测试不行?

【问题讨论】:

    标签: arrays ruby rspec


    【解决方案1】:

    您在此处定义的messagelet(:message) { double(array: [])} 与其余部分无关。

    既然你推到subject,你必须检查它。

    require 'test'
    
    describe Test do
      describe '#push' do
        it 'pushes an item into an array from the message class' do
          subject = Test.new
          subject.push("hello")
          expect(subject.message.array).to eq ["hello"]
        end
      end
    end
    

    【讨论】:

    • 啊啊啊啊不能相信我错过了!非常感谢老兄;)
    • 不客气 :) (如果它解决了您的问题,请不要犹豫将其标记为好答案)
    【解决方案2】:

    在您的 let 中,您将一个空数组分配给 message,然后测试它是否包含“hello”。那失败了,因为消息是空的。您的意思是将“hello”推送到消息数组而不是“主题”吗?

    【讨论】:

      猜你喜欢
      • 2015-12-31
      • 1970-01-01
      • 2011-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多