2013-01-24 7 views

答えて

0

Test::Unitテストは単なるRubyクラスなので、ほかのRubyクラスと同じコード再利用方法を使用できます。

共有サンプルを書き込むには、モジュールを使用できます。定義とテスト::ユニットテスト共有テストを使用する

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 

module SharedExamplesForAThing 
    def test_a_thing_does_something 
    ... 
    end 
end 

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

私は、次のコードを使用して、(RSpecのは、例を共有するために同様の)共有のテストを実施することができました
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

あなたがConcernを使用して、レール(または単にactive_support)を使用している場合。

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の使用が可能になるため、アンダースコアキーが消えないという利点があります。

関連する問題