Is there a plugin/extension similar to shared_examples in RSpec for Test::Unit tests?
If you are using rails (or just active_support), use a 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're not using active_support, just use Module#class_eval
.
This technique builds on Andy H.'s answer, where he points out that:
Test::Unit tests are just Ruby classes, so you can use [normal techniques] of code reuse
but because it enables the use of ActiveSupport::Testing::Declarative#test
it has the advantage of not wearing out your underscore key :)
I was able to implement shared tests (similar to RSpec shared 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 shared tests in a 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
Test::Unit
tests are just Ruby classes, so you can use the same methods of code reuse as any other Ruby class.
To write shared examples, you could use a module.
module SharedExamplesForAThing
def test_a_thing_does_something
...
end
end
class ThingTest < Test::Unit::TestCase
include SharedExamplesForAThing
end
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
Look at this gist 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 like this:
# memory_test.rb
require 'test_helper'
describe Memory do
it_behaves_like 'An Adapter'
end
© 2022 - 2024 — McMap. All rights reserved.