Skip to content

Instantly share code, notes, and snippets.

@jodosha
Last active August 11, 2019 03:12
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jodosha/1560208 to your computer and use it in GitHub Desktop.
Save jodosha/1560208 to your computer and use it in GitHub Desktop.
MiniTest shared examples
require 'test_helper'
shared_examples_for 'An Adapter' do
describe '#read' do
before do
@adapter.write(@key = 'whiskey', @value = "Jameson's")
end
it 'reads a given key' do
@adapter.read(@key).must_equal(@value)
end
end
end
require 'test_helper'
describe Memory do
before do
@adapter = Memory.new('memory://127.0.0.1')
end
after do
@adapter.clear
end
it_behaves_like 'An Adapter'
describe '#to_s' do
it 'returns the name' do
@adapter.to_s.must_equal('Memory')
end
end
end
require 'test_helper'
describe Redis do
before do
@adapter = Redis.new('redis://127.0.0.1:6379')
end
after do
@adapter.clear
end
it_behaves_like 'An Adapter'
describe '#to_s' do
it 'returns the name' do
@adapter.to_s.must_equal('Redis')
end
end
end
gem 'minitest'
require 'minitest/spec'
require 'minitest/autorun'
MiniTest::Spec.class_eval do
def self.shared_examples
@shared_examples ||= {}
end
end
module MiniTest::Spec::SharedExamples
def shared_examples_for(desc, &block)
MiniTest::Spec.shared_examples[desc] = block
end
def it_behaves_like(desc)
self.instance_eval(&MiniTest::Spec.shared_examples[desc])
end
end
Object.class_eval { include(MiniTest::Spec::SharedExamples) }
Copy link

ghost commented Jul 26, 2012

it_behaves_like should call the block within the context of self:

  def it_behaves_like(desc)
    self.instance_eval(&MiniTest::Spec.shared_examples[desc])
  end

Otherwise this won't work for nested describe blocks. I also modified this to define shared_examples_for and it_behaves_like on Kernel, as that's where MiniTest itself defines describe.

@rmg
Copy link

rmg commented Jun 23, 2013

I took @lgierth's comments and then took it another step further, adding support for passing a block to it_behaves_like so lets could be overridden. https://gist.github.com/rmg/5843562

@srhmgn
Copy link

srhmgn commented Jun 15, 2014

Love how all of this is set up! Can you clarify where to put adapter_test.rb?

@DanielBlanco
Copy link

Great code, thanks.

I just added a small change to support passing arguments to it_behaves_like like this:

  def it_behaves_like(desc, *args)
    self.instance_exec(*args, &MiniTest::Spec.shared_examples[desc])
  end

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