-1

例如,我有一个非常简单的卡片模型,用于流行的纸牌游戏。在初始化时,我想给它一个值和一套西装(36 张牌中的每一张都是唯一的)。这是我的模型:

class Card

  attr_accessor :suit, :value

  @@values = [6, 7, 8, 9, 10, 'B', 'D', 'K', 'T'] * 4
  @@suites = ['B', 'C', 'P', 'H'] * 9

  def initialize
    @suit = get_rundom_suit_or_value @@suites
    @value = get_rundom_suit_or_value @@values
  end

  private 

    def get_rundom_suit_or_value given_array
      given_array.delete_at(given_array.index(given_array.sample)) unless given_array.nil? || given_array.empty?
    end
end

我尝试从控制台对其进行测试,结果令人满意:

c = Card.new
 => #<Card:0x007f8e34050428 @suit="H", @value="D"> 
2.0.0-p0 :024 > c.value
 => "D" 

但是 rspec 测试并没有给我相同的结果。他们来了:

require 'spec_helper'

describe 'Card' do
  it 'has @suit value on initialize' do  
    c = Card.new
    c.suit.should_not be nil
  end
  it 'has @value value on initialize' do  
    c = Card.new
    c.value.should_not be nil
  end
end

并重新结果:

Card has @suit value on initialize
     Failure/Error: c.suit.should_not be nil

       expected not #<NilClass:8> => nil
                got #<NilClass:8> => nil

我的错误在哪里?

4

1 回答 1

1

如果我将您的代码放入一个文件并运行它,我不会收到任何错误。你所拥有的应该已经可以很好地工作了——至少它对我有用。

于 2013-08-27T06:58:17.943 回答