Sep 11

Describing Equivalence Classes in Ruby with RSpec

dastels @ 1:45 pm

Here’s an article I wrote a while ago but didn’t get around to releasing.  Enjoy. 

Describing Equivalence Classes in Ruby with RSpec

Since writing that article, I’ve made good use of the code. Here’s an example of it in action: grouping the cards in a deck into their types. A second method then uses those groups to reassemble the cards into an ordered list.

  CARD_TYPES = ['basic land', 'land', 'creature', 'artifact',
                'enchantment', 'sorcery', 'instant', '']

  def maindeck_cards_grouped
    maindeck_cards.equivalence_classes(*CARD_TYPES) do |card, the_type|
      card.magic_card.card_type.downcase.include?(the_type)
    end
  end

  def maindeck_cards_ordered
    cards_by_class = maindeck_cards_grouped
    (CARD_TYPES.inject([]) {|cards, type| cards << cards_by_class[type]}).flatten
  end

Tags: 

3 Responses to “Describing Equivalence Classes in Ruby with RSpec”

  1. Caleb Buxton says:

    Thanks for the great article!

  2. meekish says:

    Great article. I now have a much better understanding of the usefulness of ‘faking it’. One thing I noticed is that many of your examples have two or more expectations. After reading ‘One Expectation Per Example’ I’ve worked towards that goal in most of my spec suites. Did you choose to bend that rule in the article for the sake of brevity?

  3. dastels says:

    meekish,

    wrt 1 expectation per example… as you say, it’s a goal, a guideline. Sometimes it makes more sense to have multiple expectations. The key is to have each example tightly focussed.. that can often be expressed in a single expectation… but not always.

Leave a Reply