Skip to content

Instantly share code, notes, and snippets.

@steveklabnik
Created April 27, 2013 23:25
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steveklabnik/5475159 to your computer and use it in GitHub Desktop.
Save steveklabnik/5475159 to your computer and use it in GitHub Desktop.
shared examples in MiniTest As usual, "Just Use Ruby"
require 'test_helper'
describe "foo" do
include SupportsCount
end
module SupportsCount
describe "#count" do
it "is a dummy test for this example" do
assert true
end
end
end
@hannestyden
Copy link

<3

@hannestyden
Copy link

It's so simple. In this case synthetic language wins over "English".

@wojtekmach
Copy link

@steveklabnik this won't work for a more complicated example because it's immediately evaluated, eg.:

module SupportsCount
  describe "#count" do
    it "returns a natural number" do
      assert_operator @object.count, :>=, 0
    end
  end
end

We want to evaluate this only after it's included, like this:

module SupportsCount
  def self.included(base)
    describe "#count" do
    end
  end
end

There might be a way to write custom Module#describe so that we keep the DSL minimal, but I can't figure it out. Maybe defining just Module#it would be a better DSL anyway?

/cc @zenspider

@wojtekmach
Copy link

require 'minitest/autorun'

class Module
  def it(*args, &block)
    self.class.send(:define_method, :included) do |base|
      base.it(*args, &block)
    end
  end
end

module SupportsCount
  it "returns a natural number" do
    assert_operator @object.count, :>=, 0
  end
end

describe Array do
  include SupportsCount

  before do
    @object = []
  end
end

@zenspider
Copy link

For only one it per module? I don't see the point (even if it supports more than one).

@wojtekmach
Copy link

@wojtekmach
Copy link

@zenspider you probably already know that, but I was actually surprised that getting 95% use cases of shared examples with spec DSL is as simple as:

class Module
  include Minitest::Spec::DSL
end

module SupportsCount
  it 'responds to count' do
  end
end

it, before, after just works. It's kind of beautiful it's so simple. describe doesn't work but who cares.

@steveklabnik sorry for bombing your gist :p

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment