How to get common RSpec examples like behavior in Ruby Test :: Unit?

Is there a plugin / extension similar to shared_examples in RSpec for Test :: Unit tests?

+5
source share
5 answers

I managed to implement general tests (similar to common RSpec examples) using the following code:

module SharedTests
  def shared_test_for(test_name, &block)
    @@shared_tests ||= {}
    @@shared_tests[test_name] = block
  end

  def shared_test(test_name, scenario, *args)
    define_method "test_#{test_name}_for_#{scenario}" do
      instance_exec *args, &@@shared_tests[test_name]
    end
  end
end

To define and use common tests in Test :: Unit test:

class BookTest < ActiveSupport::TestCase
  extend SharedTests

  shared_test_for "validate_presence" do |attr_name|
    assert_false Books.new(valid_attrs.merge(attr_name => nil)).valid?
  end

  shared_test "validate_presence", 'foo', :foo
  shared_test "validate_presence", 'bar', :bar
end
+2
source

If you use rails (or just active_support), use Concern.

require 'active_support/concern'

module SharedTests
  extend ActiveSupport::Concern

  included do

    # This way, test name can be a string :)
    test 'banana banana banana' do
      assert true
    end

  end
end

If you are not using active_support, just use Module#class_eval.

This method is based on Andy H. , where he points out that:

Test:: - Ruby, [ ]

ActiveSupport::Testing::Declarative#test, , :)

+2

Test::Unit tests are only Ruby classes, so you can use the same code reuse methods as any other Ruby class.

To write general examples, you can use the module.

module SharedExamplesForAThing
  def test_a_thing_does_something
    ...
  end
end

class ThingTest < Test::Unit::TestCase
  include SharedExamplesForAThing
end
0
source
require 'minitest/unit'
require 'minitest/spec'
require 'minitest/autorun'

#shared tests in proc/lambda/->
basics = -> do
  describe 'other tests' do
    #override variables if necessary
    before do
      @var  = false
      @var3 = true
    end

    it 'should still make sense' do
      @var.must_equal false
      @var2.must_equal true
      @var3.must_equal true
    end
  end
end

describe 'my tests' do

  before do
    @var = true
    @var2 = true
  end

  it "should make sense" do
    @var.must_equal true
    @var2.must_equal true
  end

  #call shared tests here
  basics.call
end
0
source

Look at the meaning that I wrote a couple of years ago. It still works great: https://gist.github.com/jodosha/1560208

# adapter_test.rb
require 'test_helper'

shared_examples_for 'An Adapter' do
  describe '#read' do
    # ...
  end
end

Used as follows:

# memory_test.rb
require 'test_helper'

describe Memory do
  it_behaves_like 'An Adapter'
end
0
source

All Articles