Esiste un plug-in/estensione simile a shared_examples in RSpec per i test di Test :: Unit?Come ottengo esempi condivisi di RSpec come comportamento in Ruby Test :: Unit?
risposta
Test::Unit
test sono solo classi Ruby, quindi è possibile utilizzare gli stessi metodi di riutilizzo del codice di qualsiasi altra classe Ruby.
Per scrivere esempi condivisi, è possibile utilizzare un modulo.
module SharedExamplesForAThing
def test_a_thing_does_something
...
end
end
class ThingTest < Test::Unit::TestCase
include SharedExamplesForAThing
end
sono stato in grado di implementare i test condivisi (simile a RSpec esempi condiviso) utilizzando il seguente codice:
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
Per definire e utilizzare i test condivisi in un test di Test :: Unit:
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
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
Guarda questo che ho scritto un paio di anni fa. Funziona ancora grande: https://gist.github.com/jodosha/1560208
# adapter_test.rb
require 'test_helper'
shared_examples_for 'An Adapter' do
describe '#read' do
# ...
end
end
usati in questo modo:
# memory_test.rb
require 'test_helper'
describe Memory do
it_behaves_like 'An Adapter'
end
Se si utilizza rotaie (o semplicemente active_support), utilizzare un 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
Se non si utilizza active_support, basta usare Module#class_eval
.
Questa tecnica si basa sulla risposta Andy H. s', dove egli sottolinea che:
test Test :: Unit sono solo le classi di Ruby, in modo da poter usare [normali tecniche] di riutilizzo del codice
ma poiché abilita l'uso di ActiveSupport::Testing::Declarative#test
ha il vantaggio di non esaurire la tua chiave di sottolineatura :)