检查属性是否包含RSpec中的某个符号

时间:2016-02-18 12:25:42

标签: ruby rspec

我有一张简单的牌和套牌

class Card

  attr_accessor :suit, :rank

  def initialize(suit:, rank:)
    @suit = suit
    @rank = case rank
            when :jack then 11
            when :queen then 12
            when :king then 13
            when :ace then 14
            else rank
            end
  end
end

class Deck
  attr_accessor :cards, :suits
  SUITS = [:hearts, :diamonds, :clubs, :spades]

  def initialize
    @cards = []
    (2..14).to_a.product(SUITS).each do |arr|
      @cards << Card.new(rank: arr[0], suit: arr[1])
    end
  end


end

然后是一个简单的RSpec测试类

require 'card'


RSpec.describe Card do

  describe 'initialization' do
    let(:card) { Card.new(suit: :hearts, rank: 10) }

    it 'can be made' do
      expect(card.suit).to eq(:spadess).or eq(:hearts).or eq(:diamonds)
    end
  end
end

RSpec.describe Deck do 
  describe 'count' do 
    let(:cards) { Deck.new().cards }
    let(:deck) { Deck.new() }

    it 'is 52' do
      expect(cards.count).to eq(52)
    end

    it 'all has a rank greater than 1' do 
      expect(cards).to all(have_attributes(rank: be >= 1 && be <= 14)).and all(have_attributes(suit: (be == :spades || be == :hearts || be == :diamonds || be ==:clubs) ))
    end

  end
end

我正在尝试使用Rspec来比较所有等级都在一定范围内(这是有效的)但是我遇到的麻烦是检查每个套装是否与4个套装简单中的一个匹配,以下产生错误:< / p>

object at index 48 failed to match:
  expected #<Card:0x007fbadc0fade0 @suit=:hearts, @rank=14> to have attributes {:suit => (be == spades)}

1 个答案:

答案 0 :(得分:2)

(be == :spades || be == :hearts || be == :diamonds || be ==:clubs)

相当于

(be == :spades)

因此出现错误消息

... to have attributes {:suit => (be == spades)}
                                 ^^^^^^^^^^^^^^

您必须使用RSpec的or方法来链接期望:

((be == :spades).or (be == :hearts).or (be == :diamonds).or (be == :clubs))

如果实现了一些谓词方法:

class Card
  # ...

  def hearts?
    suit == :hearts
  end

  # same for spades, diamonds and clubs
end

你可以更自然地表达你的意图:

 it 'contains only hearts, spades, diamonds or clubs' do
   expect(cards).to all(be_hearts.or be_spades.or be_diamonds.or be_clubs)
 end