【问题标题】:RSpec expectations from(...).to(...) returning errorRSpec 期望 from(...).to(...) 返回错误
【发布时间】:2014-07-11 14:20:20
【问题描述】:

我有以下代码:

it 'draws one h-segment of colour C' do
  editor.send :create_image, 3, 2
  pp editor.image

  expect {
    pp editor.image # => [["O", "O", "O"], ["O", "O", "O"]]
    editor.send :draw_horizontal, 0, 1, 0, 'C'
    pp editor.image # => [["C", "C", "O"], ["O", "O", "O"]]
  }.to change{
    editor.image
  }.
  from([["O", "O", "O"], ["O", "O", "O"]]). 
  to   [["C", "C", "O"], ["O", "O", "O"]]

end

因为调用方法 :draw_horizontal 之前和之后的两行都返回了我在 fromto 匹配器中的内容,所以我希望测试能够通过。

实际上,我得到了这个错误:

Failure/Error: expect {
   expected result to have initially been [["O", "O", "O"], ["O", "O", "O"]], but was [["C", "C", "O"], ["O", "O", "O"]]

我也尝试删除from,只留下to,但结果是这样

Failure/Error: expect {
   expected result to have changed to [["C", "C", "O"], ["O", "O", "O"]], but did not change

任何想法如何解决它?谢谢

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:

    我尝试了@benjamin-sinclaire 建议的解决方案,但很遗憾没有奏效。

    为了解决这个问题,我必须评估Array.to_s 而不是它本身的值。 我不知道这是否是在比较变量@image 的内容,按引用而不是按值传递。

    it 'draws one h-segment of colour C' do
      expect {
        editor.send(:draw_horizontal, 0, 1, 0, 'C')
      }.to change { editor.image.to_s }.
      from([["O", "O", "O"], ["O", "O", "O"]].to_s).
      to   [["C", "C", "O"], ["O", "O", "O"]].to_s
    
    end
    

    这种方式效果很好,但是如果您找到其他(更好的)解决方案和解释,请在下面发表评论。

    【讨论】:

    • 干得好。更简洁的方法是使用inspect。它在数组上给出了相同的结果,但使用inspect 是一个好习惯,因为它几乎适用于 Ruby 中的所有内容。
    【解决方案2】:

    这是一个盲目的猜测,但试试这个

    describe 'isolate this block to use `subject`' do # You'll have to name this accordingly
      subject { editor }
      before { editor.send :create_image, 3, 2 }
      it 'draws one h-segment of colour C' do
        expect { editor.send :draw_horizontal, 0, 1, 0, 'C' }.
        to change(:image).
        from([["O", "O", "O"], ["O", "O", "O"]]). 
        to   [["C", "C", "O"], ["O", "O", "O"]]
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2017-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 2018-09-14
      • 1970-01-01
      • 2021-06-21
      相关资源
      最近更新 更多