2013-01-24 22 views

回答

0

Test::Unit測試只是Ruby類,因此您可以使用與其他任何Ruby類相同的代碼重用方法。

要編寫共享示例,您可以使用一個模塊。

module SharedExamplesForAThing 
    def test_a_thing_does_something 
    ... 
    end 
end 

class ThingTest < Test::Unit::TestCase 
    include SharedExamplesForAThing 
end 
2

我能夠實現共享試驗(類似於RSpec的共享實施例)使用下面的代碼:

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 

要定義和在測試::單元測試使用共享測試:

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 
0
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

看看我在幾年前寫的這個要點。它仍然偉大工程:https://gist.github.com/jodosha/1560208

# adapter_test.rb 
require 'test_helper' 

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

像這樣來使用:

# memory_test.rb 
require 'test_helper' 

describe Memory do 
    it_behaves_like 'An Adapter' 
end 
2

如果您正在使用的軌道(或只是active_support),使用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 

如果您不使用active_support,只需使用Module#class_eval即可。

這種技術建立在Andy H.的回答,他指出:

測試::單元測試只是Ruby類,所以你可以使用[普通技術]代碼重用的

但是因爲它能夠使用ActiveSupport::Testing::Declarative#test它的好處是不會穿出你的下劃線鍵:)