简体   繁体   English

Ruby rspec 推入阵列时出错

[英]Ruby rspec error for pushing into an array

Im trying to pass a test for pushing an item into an array from another class.我试图通过将项目从另一个 class 推入数组的测试。 Here is the method.这是方法。

require_relative 'message'

class Test

  attr_reader :message

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

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

The empty array in a different class.不同的 class 中的空数组。

class Message

  attr_reader :array 

  def initialize
    @array = []
  end
end

and my test.和我的测试。

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

currenty getting the error目前收到错误

expected: ["hello"]
     got: []

       (compared using ==)

what am i doing wrong?我究竟做错了什么? The method itself is simple and works, why does my test not?该方法本身很简单并且有效,为什么我的测试没有?

The message you defined here: let(:message) { double(array: [])} has nothing to do with the rest.您在此处定义的messagelet(:message) { double(array: [])}与 rest 无关。

Since you pushed into subject you have to check on it.既然你推入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

In your let, you assign an empty array to message and then test if it contains 'hello'.在您的 let 中,您为 message 分配一个空数组,然后测试它是否包含“hello”。 That fails because message is empty.那失败了,因为消息是空的。 Did you mean to push 'hello' to the message array instead of to 'subject'?您的意思是将“你好”推送到消息数组而不是“主题”吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM