Ruby rspec 推入数组时出错

Ruby rspec error for pushing into an array

我正在尝试通过将一个项目从另一个 class 推入数组的测试。 方法在这里。

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中的空数组。

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 ==)

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

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

您在此处定义的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