为什么我在新的rspec版本中不能使用expect

时间:2015-02-05 15:54:20

标签: ruby rspec

我是ruby代码的新手。我的团队成员写了一个实现游戏集的类Deck

class Deck
  @array = Array.new

  # create a deck of n cards
  # n <= 0 returns empty array.
  def initialize (n=1)
    @array = (0..n-1).to_a
  end
end

我正在尝试编写rspec测试,这对我们来说也是新的,这里是测试代码:

#!/user/bin/ruby -w
require '../deck'
require 'rspec/expectations'

describe "Deck#new" do
  context "with one parameter " do
    it "has parameter n = 0" do 
      expect(Deck.new(0)).to match_array([])
    end

    it "has parameter n = 1" do
      expect(Deck.new(1)).to eq([0])
    end

    it "has parameter n = 5" do
      expect(Deck.new(5))==([0,1,2,3,4])
    end

    it "has parameter n<0" do
      expect(Deck.new(-1))==([])
    end
  end
end

但是当我运行这个测试时,它给了我

expected a collection that can be converted to an array with `#to_ary` or `#to_a`, but got #<Deck:0xb82edb74 @array=[]> 

前两个失败,我不明白。我在代码中遗漏了什么吗?感谢帮助。我的rspec版本是最新版本。

1 个答案:

答案 0 :(得分:2)

您需要一种方法来访问卡片:

class Deck
  def initialize (n=1)
    @array = (0..n-1).to_a
  end
  def cards
    @array
  end
end

这样:

Deck.new(5).cards
#=> [0, 1, 2, 3, 4]

因此,请将测试更改为:

it "has parameter n = 0" do 
 expect(Deck.new(0).cards).to match_array([])
end

依旧......

更新:
Deck.new(n)返回整个对象

Deck.new(5)
=> #<Deck:0x007fb56b0e82b0 @array=[0, 1, 2, 3, 4]>

因此,您的测试将失败...整个对象与@array[0, 1, 2, 3, 4])的内容不同。

更新2:
您可以定义任何新方法,例如卡片中的os卡号:

class Deck
  def initialize (n=1)
    @array = (0..n-1).to_a
  end
  def cards
    @array
  end
  def number_of_cards
    @array.size
  end
end

Deck.new(5).number_of_cards
#=> 5
相关问题