【问题标题】:How to test not ActiveRecord models with rspec?如何使用 rspec 测试非 ActiveRecord 模型?
【发布时间】:2013-08-27 06:27:37
【问题描述】:

例如,我有一个非常简单的纸牌模型,用于流行的纸牌游戏。在初始化时,我想给它一个值和一套花色(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

我的错误在哪里?

【问题讨论】:

  • c.suit.should_not be_nil
  • expected: not nil got: nil
  • spec_helper.rb 中有什么内容?您是否在某处定义了另一个 Card 类?

标签: ruby rspec


【解决方案1】:

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

【讨论】:

  • 同样的错误Card suit should not be nil Failure/Error: its(:suit) { should_not be_nil } expected: not nil got: nil 我在控制台中仔细检查了这个,仍然得到这个错误。从控制台我得到2.0.0-p0 :001 &gt; c = Card.new =&gt; #&lt;Card:0x007fefcc83fce8 @suit="B", @value="T"&gt;
  • 对不起,您的原始语法非常好。事实上,当我运行它时,您的代码运行良好。没有规范失败,只有成功。更改我的答案以反映这一点。
  • 你是对的,我将它作为一个文件测试,在 Rails ENV 之外,我得到了成功:)。 Jakob S 评论也许是这个问题的答案。 Card class somewhere? – 1 hour ago
猜你喜欢
  • 2017-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-04
  • 1970-01-01
  • 1970-01-01
  • 2017-07-17
  • 1970-01-01
相关资源
最近更新 更多