clean-test-1.0.0/ 0000755 0001750 0001750 00000000000 13017326460 012475 5 ustar micah micah clean-test-1.0.0/lib/ 0000755 0001750 0001750 00000000000 13017326460 013243 5 ustar micah micah clean-test-1.0.0/lib/clean_test/ 0000755 0001750 0001750 00000000000 13017326460 015364 5 ustar micah micah clean-test-1.0.0/lib/clean_test/version.rb 0000644 0001750 0001750 00000000115 13017326460 017373 0 ustar micah micah module Clean #:nodoc:
module Test #:nodoc:
VERSION = "1.0.0"
end
end
clean-test-1.0.0/lib/clean_test/any.rb 0000644 0001750 0001750 00000012136 13017326460 016503 0 ustar micah micah require 'faker'
module Clean #:nodoc:
module Test #:nodoc:
# Public: Provides the ability to vend arbitrary values without using literals, or
# long calls to Faker. This produced random values, so you must be sure that your code truly
# should work with any value. The random seed used will be output, and you can use
# the environment variable +RANDOM_SEED+ to recreate the conditions of a particular test.
#
# Example:
#
# class Person
# def initialize(first_name,last_name,age)
# # ...
# end
# end
#
# test_that "someone under 18 is a minor" {
# Given {
# # First name and last name aren't relevant to the test
# @person = Person.new(any_string,any_string,17)
# }
# When {
# @minor = @person.minor?
# }
# Then {
# assert @minor
# }
# }
#
# test_that "full_name gives the full name" {
# Given {
# # Age isn't relevant; it just needs to be positive
# @person = Person.new("Dave","Copeland",any_int :positive)
# }
# When {
# @full_name = @person.full_name
# }
# Then {
# assert_equal "Dave Copeland",@full_namej
# }
# }
module Any
def self.setup_random_seed
seed = if ENV['RANDOM_SEED']
ENV['RANDOM_SEED'].to_i
else
srand() # generate random seed
seed = srand() # save it (but we've now generated another one)
end
srand(seed) # set it explicitly
puts "Random seed was #{seed}; re-use it via environment variable RANDOM_SEED"
end
setup_random_seed
MAX_RAND = 50000 #:nodoc:
# Public: Get any number; one that doesn't matter
#
# options - options to control what sort of number comes back:
# :positive - make sure that the number is greater than zero
# :negative - make sure that the number is less than zero
def any_number(*options)
number = (rand(2 * MAX_RAND) - MAX_RAND).to_f/100.0
if options.include? :positive
number + MAX_RAND
elsif options.include? :negative
number - MAX_RAND
else
number
end
end
# Public: Returns an integer. options is the same as for #any_number
def any_int(*options)
any_number(*options).to_i
end
# Public: Get an arbitrary string of any potential positive length
#
# options - options to control the returned string:
# :max - the max size of the string you want, must be positive and greater than :min
# :min - the minimum size we want to come back, must be positive and less than :max
#
# Example
#
# any_string :max => 255 # => ensure it'll fit into a varchar(255)
# any_string :min => 1024 # at least 1024 characters
#
def any_string(options = {})
if options[:min] && options[:max]
raise ":min must be less than :max" if options[:min] > options[:max]
end
if options[:min]
raise ":min must be positive" if options[:min] < 1
end
min_size = options[:min]
max_size = options[:max]
if min_size.nil? && max_size.nil?
min_size = rand(80) + 1
max_size = min_size + rand(80)
elsif min_size.nil?
min_size = max_size - rand(max_size)
min_size = 1 if min_size < 1
else
max_size = min_size + rand(min_size) + 1
end
string = Faker::Lorem.words(1).join(' ')
while string.length < min_size
string += Faker::Lorem.words(1).join(' ')
end
string[0..(max_size-1)]
end
# Public: Get an arbitrary symbol, for example to use as a Hash key. The symbol
# will be between 2 and 20 characters long. If you need super-long symbols for some reason,
# use any_string.to_sym
.
def any_symbol
(any_string :min => 2, :max => 20).to_sym
end
# Public: Get an arbitrary sentence of arbitrary words of any potential length. Currently,
# this returns a sentence between 10 and 21 words, though you can control that with options
#
# options - options to control the returned sentence
# :max - the maximum number of words you want returned
# :min - the minimum number of words you want returned; the sentence will be between
# :min and (:min + 10) words
#
# Example
#
# any_sentence :min => 20 # at least a 20-word sentence
# any_sentence :max => 4 # no more than four words
#
def any_sentence(options = {})
min = 11
max = 21
if options[:max]
min = 1
max = options[:max]
elsif options[:min]
min = options[:min]
max = min + 10
end
Faker::Lorem.words(rand(max - min) + min).join(' ')
end
end
end
end
clean-test-1.0.0/lib/clean_test/test_that.rb 0000644 0001750 0001750 00000006300 13017326460 017707 0 ustar micah micah module Clean #:nodoc:
module Test #:nodoc:
# Public: Module that, when included, makes a class method, +#test_that+ available
# to create test methods in a more fluent way. See ClassMethods.
module TestThat
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
# Public: Create a new test method with the given optional description and
# body.
#
# description - a string describing what is being tested; write this as a follow on
# from the phrase "test that". If nil, a name will be constructed
# based on the block
# block - the body of the test.
#
# Example
#
# # Create a rails-style test method
# test_that "area is computed based on positive radius" do
# Given {
# @circle = Circle.new(10)
# }
# When {
# @area = @circle.area
# }
# Then {
# assert_equal 314,@area
# }
# end
#
# # Create an "anonymous" test, where the test body
# # is clear enough as to what's being tested
# test_that {
# Given a_circle(:radius => 10)
# When get_area
# Then area_should_be(314)
# }
def test_that(description=nil,&block)
raise "You must provide a block" if block.nil?
description = make_up_name(block) if description.nil?
test_name = "test_#{description.gsub(/\s+/,'_')}".to_sym
defined = instance_method(test_name) rescue false
raise "#{test_name} is already defined in #{self}" if defined
define_method(test_name, &block)
end
# Public: Create a test that you don't want to actually run.
# This can be handy if you want to temporarily keep a test from
# running, but don't want to deal with comments or if (false) blocks.
# Tests skipped this way will generate a warning to the standard error.
# Arguments are indentical to #test_that
def skip_a_test_that(description=nil,&block)
description = make_up_name(block) if description.nil?
STDERR.puts "warning: test 'test that #{description}' is being skipped" unless $FOR_TESTING_ONLY_SKIP_STDERR
end
# Public: Create a test that is pending or that you intend to implement soon.
# This can be handy for sketching out some tests that you want, as this will
# print the pending tests to the standard error
def someday_test_that(description=nil,&block)
description = make_up_name(block) if description.nil?
STDERR.puts "warning: test 'test that #{description}' is pending" unless $FOR_TESTING_ONLY_SKIP_STDERR
end
private
def make_up_name(some_proc)
if some_proc.respond_to? :source_location
name,location = some_proc.source_location
"anonymous test at #{name}, line #{location} passes"
else
"anonymous test for proc #{some_proc.object_id} passes"
end
end
end
end
end
end
clean-test-1.0.0/lib/clean_test/given_when_then.rb 0000644 0001750 0001750 00000014075 13017326460 021067 0 ustar micah micah module Clean #:nodoc:
module Test #:nodoc:
# A means of documenting the parts of your test code according
# to the class "Given/When/Then" system.
# This does no enforcement of any kind and is merely documentation to make
# your tests readable.
#
# Example:
#
# Given {
# @circle = Circle.new(10)
# }
# When {
# @area = @circle.area
# }
# Then {
# assert_equal 314,@area
# }
#
# There are also two additional methods provided ,#the_test_runs and
# #mocks_shouldve_been_called to assist with creating readable tests that use mocks. See those
# methods for an example
module GivenWhenThen
# Public: Declare a step in your test, based on the following conventions:
#
# Given - This sets up conditions for the test
# When - This executes the code under test
# Then - This asserts that that the code under test worked correctly
# And - Extend a Given/When/Then when using lambda/method form (see below)
# But - Extend a Given/When/Then when using lambda/method form (see below)
#
# There are three forms for calling this method, in order of preference:
#
# block - in this form, you pass a block that contains the test code. This should be preferred as it
# keeps your test code in your test
# method - in this form, you pass a symbol that is the name of a method in your test class. This method
# should set up or perform or assert whatever is needed. This can be useful to re-use test helper
# methods in an expedient fashion. In this case, you can pass parameters by simply listing
# them after the symbol. See the example.
# lambda - in this form, you declare a method that returns a lambda and that is used as the
# block for this step of the test. This is least desirable, as it requires methods to return
# lambdas, which is an extra bit of indirection that adds noise.
#
# Parameters:
#
# existing_block - a callable object (e.g. a Proc) that will be called immediately
# by this Given. If this is a Symbol, a method in the current scope will be converted into
# a block and used. If nil, &block is expected to be passed
# other_args - a list of arguments to be passed to the block. This is mostly useful when using method form.
# block - a block given to this call that will be executed immediately
# by this Given. If existing_block is non-nil, this is ignored
#
# Examples
#
# # block form
# Given {
# @foo = "bar"
# }
#
# # method form
# def assert_valid_person
# assert @person.valid?,"Person invalid: #{@person.errors.full_messages}"
# end
#
# Given {
# @person = Person.new(:last_name => 'Copeland', :first_name => 'Dave')
# }
# Then :assert_valid_person
#
# # method form with arguments
# def assert_invalid_person(error_field)
# assert !@person.valid?
# assert @person.errors[error_field].present?
# end
#
# Given {
# @person = Person.new(:last_name => 'Copeland')
# }
# Then :assert_invalid_person,:first_name
#
# # lambda form
# def assert_valid_person
# lambda {
# assert @person.valid?,"Person invalid: #{@person.errors.full_messages}"
# }
# end
#
# Given {
# @person = Person.new(:last_name => 'Copeland', :first_name => 'Dave')
# }
# Then assert_valid_person
#
# Returns the block that was executed
def Given(existing_block=nil,*other_args,&block)
if existing_block.nil?
block.call(*other_args)
block
else
if existing_block.kind_of?(Symbol)
existing_block = method(existing_block)
end
existing_block.call(*other_args)
existing_block
end
end
# Public: Execute the code under test. Behavior identical to Given
alias :When :Given
# Public: Assert the results of the test. Behavior identical to Given
alias :Then :Given
# Public: Extend a Given/When/Then when using method or lambda form. Behavior identical to Given
alias :And :Given
# Public: Extend a Given/When/Then when using method or lambda form. Behavior identical to Given
alias :But :Given
# Public: Used to make clear the structure of tests using mocks.
# This returns a no-op, and is intended to be used with a "When"
# to delineate the creation of a mock in a Given, and the
# expectations of a mock in a "Then"
#
# Example:
#
# Given {
# @google = mock()
# }
# When the_test_runs
# Then {
# @google.expects(:search).with('foo').returns('bar')
# }
# Given {
# @my_search = Search.new(@google)
# }
# When {
# @result = @my_search.find('foo')
# }
# Then {
# assert_equal 'Found bar',@result
# }
# And mocks_shouldve_been_called
def the_test_runs
lambda {}
end
# Public: Similar to #the_test_runs, this is used to make clear what
# you are testing and what the assertions are. Since many Ruby mock
# frameworks do not require an explicit "verify" step, you often have tests
# that have no explicit asserts, the assertions being simply that the mocks were called
# as expected. This step, which is a no-op, allows you to document that you are
# expecting mocks to be called (rather than forgot to assert anything).
# See the example in #mocks_are_called for usage.
def mocks_shouldve_been_called
lambda {}
end
end
end
end
clean-test-1.0.0/lib/clean_test/test_case.rb 0000644 0001750 0001750 00000001507 13017326460 017666 0 ustar micah micah require 'test/unit'
require 'clean_test/given_when_then'
require 'clean_test/any'
require 'clean_test/test_that'
module Clean #:nodoc:
module Test #:nodoc:
# Public: A Base class brings in all modules that are part
# of Clean::Test.
#
# Example
#
# class TestCircle < Clean::Test::TestCase
# test_that {
# Given { @circle = Circle.new(10) }
# When { @area = @circle.area }
# Then { assert_equal 314,@area }
# }
# end
class TestCase < ::Test::Unit::TestCase
include GivenWhenThen
include TestThat
include Any
if RUBY_VERSION =~ /^1\.8\./
# Avoid the stupid behavior of
# complaining that no tests were specified for 1.8.-like rubies
def default_test
end
end
end
end
end
clean-test-1.0.0/.gitignore 0000644 0001750 0001750 00000000066 13017326460 014467 0 ustar micah micah *.gem
.bundle
Gemfile.lock
pkg/*
coverage
html
.*.sw?
clean-test-1.0.0/test/ 0000755 0001750 0001750 00000000000 13017326460 013454 5 ustar micah micah clean-test-1.0.0/test/test_test_that.rb 0000644 0001750 0001750 00000001426 13017326460 017042 0 ustar micah micah require 'test/unit'
require 'clean_test/test_case'
class TestSimpleGiven < Clean::Test::TestCase
test_that "when assigning @x to 4, it is 4" do
Given {
@x = nil
}
When {
@x = 4
}
Then {
assert_equal 4,@x
}
end
test_that {
Given {
@x = nil
}
When {
@x = 4
}
Then {
assert_equal 4,@x
}
}
$FOR_TESTING_ONLY_SKIP_STDERR = true
skip_a_test_that "a skipped test isn't called" do
raise "This shouldn't happen!"
end
someday_test_that "a pending test isn't called" do
raise "This shouldn't happen, either!"
end
$FOR_TESTING_ONLY_SKIP_STDERR = false
def test_that_test_that_barfs_with_no_block
assert_raises RuntimeError do
self.class.test_that "foo"
end
end
end
clean-test-1.0.0/test/test_circle.rb 0000644 0001750 0001750 00000000514 13017326460 016301 0 ustar micah micah require 'clean_test/test_case'
class Circle
def initialize(radius)
@radius = radius
end
def area; (3.14 * @radius * @radius).to_i; end
end
class TestCircle < Clean::Test::TestCase
test_that {
Given { @circle = Circle.new(10) }
When { @area = @circle.area }
Then { assert_equal 314,@area }
}
end
clean-test-1.0.0/test/test_given_when_then.rb 0000644 0001750 0001750 00000003630 13017326460 020211 0 ustar micah micah require 'test/unit'
require 'clean_test/test_case'
class TestGivenWhenThen < Clean::Test::TestCase
def test_basics
Given {
@x = nil
}
And {
@y = nil
@z = 10
}
When {
@x = 4
}
And {
@y = 10
}
But {
@z # not assigned
}
Then {
assert_equal 4,@x
}
And {
assert_equal 10,@y
}
But {
assert_equal 10,@z
}
end
def test_mock_support
Given { @x = 4 }
When the_test_runs
Then { }
Given { @y = 4 }
When { @y = 10 }
Then { assert_equal 10,@y }
And mocks_shouldve_been_called
end
def test_cannot_use_locals
Given {
@x = nil
}
When {
x = 4
}
Then {
assert_nil @x
refute defined? x
}
end
def test_can_reuse_blocks
invocations = 0
x_is_nil = Given {
@x = nil
invocations += 1
}
x_is_assigned_to_four = When {
@x = 4
invocations += 1
}
x_should_be_four = Then {
assert_equal 4,@x
invocations += 1
}
Given x_is_nil
When x_is_assigned_to_four
Then x_should_be_four
assert_equal 6,invocations
end
def test_methods_that_return_blocks
Given a_nil_x
When {
@x = 4
}
Then {
assert_equal 4,@x
}
end
def test_can_use_symbols_for_methods
Given :a_string
Then {
assert_equal "foo",@string
}
end
def test_can_pass_params_to_symbols
Given :a_string, 4
Then {
assert_equal 4,@string.length
}
end
def test_invert_for_block_based_asserts
Given a_nil_x
Then {
assert_raises NoMethodError do
When {
@x + 4
}
end
}
end
private
def a_string(length=3)
if length == 3
@string = "foo"
else
@string = "quux"
end
end
def a_nil_x
Proc.new { @x = nil }
end
def refute(bool_expr)
assert !bool_expr
end
end
clean-test-1.0.0/test/test_any.rb 0000644 0001750 0001750 00000005401 13017326460 015627 0 ustar micah micah require 'test/unit'
require 'clean_test/test_case'
class TestAny < Clean::Test::TestCase
def setup
# Fix the seed to be the same all day so our tests are repeatable
srand((Time.now.to_i / (1000 * 60 * 60)))#.tap { |_| puts "seed: #{_}" })
end
test_that {
When { @number = any_number }
Then { assert_not_nil @number }
}
test_that {
When { @number = any_number :positive }
Then { assert @number > 0,"We specified :positive, but got a negative" }
}
test_that {
When { @number = any_number :negative }
Then { assert @number < 0,"We specified :negative, but got a positive" }
}
test_that {
When { @number = any_int }
Then {
assert_not_nil @number
assert_equal @number.to_i,@number,"Expected an int, not a #{@number.class}"
}
}
test_that {
When { @int = any_int :positive }
Then { assert @int > 0,"We specified :positive, but got a negative" }
}
test_that {
When { @int = any_int :negative }
Then { assert @int < 0,"We specified :negative, but got a positive" }
}
test_that {
When { @string = any_string }
Then {
assert_not_nil @string
assert_equal String,@string.class
}
}
test_that {
When { @string = any_string :max => 255 }
Then {
assert_equal String,@string.class
assert @string.length <= 255,"Expected a string of less than 256 characters, got #{@string.length}"
}
}
test_that {
When { @string = any_string :min => 1000 }
Then {
assert_equal String,@string.class
assert @string.length >= 1000,"Expected a string of at least 1000 characters, got one of #{@string.length} characters"
}
}
test_that "min and max must agree" do
When {
@code = lambda { @string = any_string :min => 10, :max => 3 }
}
Then {
assert_raises(RuntimeError,&@code)
}
end
[
[-10, 1],
[ 0, 1],
[ 0, 0],
[ 0,-10],
].each do |(min,max)|
test_that "both min and max must be positive (#{min},#{max})" do
When {
@code = lambda { @string = any_string :min => min, :max => max }
}
Then {
assert_raises(RuntimeError,&@code)
}
end
end
test_that {
When { @sentence = any_sentence }
Then { assert @sentence.split(/\s/).size > 10,@sentence }
}
test_that {
When { @sentence = any_sentence :max => 5 }
Then { assert @sentence.split(/\s/).size <= 5,@sentence }
}
test_that {
When { @sentence = any_sentence :min => 20 }
Then { assert @sentence.split(/\s/).size >= 20,@sentence }
}
test_that "any_symbol works" do
When {
@symbol = any_symbol
}
Then {
assert_not_nil @symbol
assert @symbol.kind_of? Symbol
assert @symbol.to_s.length < 20
}
end
end
clean-test-1.0.0/test/bootstrap.rb 0000644 0001750 0001750 00000000106 13017326460 016013 0 ustar micah micah require 'simplecov'
SimpleCov.start do
add_filter "/test/*.rb"
end
clean-test-1.0.0/LICENSE.txt 0000644 0001750 0001750 00000026135 13017326460 014327 0 ustar micah micah Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
clean-test-1.0.0/README.rdoc 0000644 0001750 0001750 00000031074 13017326460 014310 0 ustar micah micah = Clean Tests
Author:: Dave Copeland (mailto:davetron5000 at g mail dot com)
Copyright:: Copyright (c) 2012 by Dave Copeland
License:: Distributes under the Apache License, see LICENSE.txt in the source distro
Get your Test::Unit test cases readable and fluent, without RSpec, magic, or crazy meta-programming.
This library is a set of small, simple tools to make your Test::Unit test cases easy to understand. This isn't a massive change in how you write tests, but simply some helpful things will make your tests easier to read.
* {Source}[http://www.github.com/davetron5000/clean_test]
* {RDoc}[http://davetron5000.github.com/clean_test/rdoc]
The main problems this library solves are:
* Understanding what part of a test method is setup, test, and evaluation
* Understanding what elements of a test are relevant to the test, and which are arbitrary placeholders
* Removing the requirement that your tests are method names
== Install
gem install clean_test
Or, with bundler:
gem "clean_test", :require => false
== Overview
class Circle
attr_reader :name
attr_reader :radius
def initialize(radius,name)
@radius = radius
@name = name
end
def area
@radius * @radius * 3.14
end
def to_s
"circle of radius #{radius}, named #{name}"
end
end
require 'clean_test/test_case'
class CircleTest < Clean::Test::TestCase
test_that "area is computed correctly" {
Given {
@circle = Circle.new(10,any_string)
}
When {
@area = @circle.area
}
Then {
assert_equal 314,@area
}
}
test_that "to_s includes the name" {
Given {
@name = "foo"
@circle = Circle.new(any_int,@name)
}
When {
@string = @circle.to_s
}
Then {
assert_match /#{@name}/,@string
}
}
end
What's going on here?
* We can clearly see which parts of our test are setting things up (stuff inside +Given+), which parts are executing the code we're testing (stuff in +When+) and which parts are evalulating the results (stuff in +Then+)
* We can see which values are relevant to the test - only those that are literals. In the first test, the +name+ of our circle is not relevant to the test, so instead of using a dummy value like "foo", we use +any_string+, which makes it clear that the value does not matter. Similarly, in the second test, the radius is irrelevant, so we use +any_int+ to signify that it doesn't matter.
* Our tests are clearly named and described with strings, but we didn't need to bring in active support.
* A side effect of this structure is that we use instance vars to pass data between Given/When/Then blocks. This means that instance vars "jump out" as important variables to the test; non-instance vars "fade away" into the background.
But, don't fret, this is not an all-or-nothing proposition. Use whichever parts you like. Each feature is in a module that you can include as needed, or you can do what we're doing here and extend Clean::Test::TestCase to get everything at once.
== More Info
* Clean::Test::TestCase is the base class that gives you everything
* Clean::Test::GivenWhenThen provides the Given/When/Then construct
* Clean::Test::TestThat provides +test_that+
* Clean::Test::Any provides the +any_string+ and friends.
== Questions you might have
=== Why?
I'm tired of unreadable tests. Tests should be good, clean code, and it shoud be easy to see what's being tested. This is especially important when there is a lot of setup required to simulate something.
I also don't believe we need to resort to a lot of metaprogramming tricks just to get our tests in this shape. RSpec, for example, creates strange constructs for things that are much more straightforward in plain Ruby. I like Test::Unit, and with just a bit of helper methods, we can make nice, readable tests, using just Ruby.
=== But the test methods are longer!
And? I don't mind a test method that's a bit longer if that makes it easy to understand. Certainly, a method like this is short:
def test_radius
assert_equal 314,Circle.new(10).radius
end
But, we rarely get such simple methods *and* this test method isn't very modifiable; everything is on one line and it doesn't encourage re-use. We can do better.
=== What about mocks?
Mocks create an interesting issue, because the "assertions" are the mock expectations you setup before you call the method under test. This means that the "then" side of things is out of order.
class CircleTest < Test::Unit::Given::TestCase
test_that "our external diameter service is being used" do
Given {
@diameter_service = mock()
@diameter_service.expects(:get_diameter).with(10).returns(400)
@circle = Circle.new(10,@diameter_service)
}
When {
@diameter = @circle.diameter
}
Then {
// assume mocks were called
}
end
end
This is somewhat confusing. We could solve it using two blocks provided by this library, +the_test_runs+, and +mocks_shouldve_been_called+, like so:
class CircleTest < Test::Unit::Given::TestCase
test_that "our external diameter service is being used" do
Given {
@diameter_service = mock()
}
When the_test_runs
Then {
@diameter_service.expects(:get_diameter).with(10).returns(400)
}
Given {
@circle = Circle.new(10,@diameter_service)
}
When {
@diameter = @circle.diameter
}
Then mocks_shouldve_been_called
end
end
Although both the_test_runs and mocks_shouldve_been_called are no-ops,
they allow our tests to be readable and make clear what the assertions are that we are making.
Yes, this makes our test a bit longer, but it's *much* more clear.
=== What about block-based assertions, like +assert_raises+
Again, things are a bit out of order in a class test case, but you can clean this up without this library or any craziness, by just using Ruby:
class CircleTest < Clean::Test::TestCase
test_that "there is no diameter method" do
Given {
@circle = Circle.new(10)
}
When {
@code = lambda { @circle.diameter }
}
Then {
assert_raises(NoMethodError,&@code)
}
end
end
=== My tests require a lot of setup, so I use contexts in shoulda/RSpec. What say you?
Duplicated setup can be tricky. A problem with heavily nested contexts in Shoulda or RSpec is that it can be hard to piece together what all the "Givens" of a particular test actually are. As a reaction to this, a lot of developers tend to just duplicate setup code, so that each test "stands on its own". This makes adding features or changing things difficult, because it's not clear what duplicated code is the same by happenstance, or the same because it's *supposed* to be the same.
To deal with this, we simply use Ruby and method extraction. Let's say we have a +Salutation+ class that takes a +Person+ and a +Language+ in its constructor, and then provides methods to "greet" that person
class Salutation
def initialize(person,language)
raise "person required" if person.nil?
raise "language required" if language.nil?
end
# ... methods
end
To test this class, we always need a non-nil person and language. We might end up with code like this:
class SalutationTest << Clean::Test::TestCase
test_that "greeting works" do
Given {
person = Person.new("David","Copeland",:male)
language = Language.new("English","en")
@salutation = Salutation.new(person,language)
}
When {
@greeting = @salutation.greeting
}
Then {
assert_equal "Hello, David!",@salutation.greeting
}
end
test_that "greeting works for no first name" do
Given {
person = Person.new(nil,"Copeland",:male)
language = Language.new("English","en")
@salutation = Salutation.new(person,language)
}
When {
@greeting = @salutation.greeting
}
Then {
assert_equal "Hello, Mr. Copeland!",@salutation.greeting
}
end
end
In both cases, the language is the same, and the person is slightly different. Method extraction:
class SalutationTest << Clean::Test::TestCase
test_that "greeting works" do
Given {
@salutation = Salutation.new(male_with_first_name("David"),english)
}
When {
@greeting = @salutation.greeting
}
Then {
assert_equal "Hello, David!",@salutation.greeting
}
end
test_that "greeting works for no first name" do
Given {
@salutation = Salutation.new(male_with_no_first_name("Copeland"),english)
}
When {
@greeting = @salutation.greeting
}
Then {
assert_equal "Hello, Mr. Copeland!",@salutation.greeting
}
end
private
def male_with_first_name(first_name)
Person.new(first_name,any_string,:male)
end
def male_with_no_first_name(last_name)
Person.new(nil,last_name,:male)
end
def english; Language.new("English","en"); end
end
=== What did that have to do with this gem?
Nothing. That's the point. You have the power already. That being said, +Given+ and friends can take a symbol representing the name of a method to call, in lieu of a block:
class SalutationTest << Clean::Test::TestCase
test_that "greeting works" do
Given :english_salutation_for,male_with_first_name("David")
When {
@greeting = @salutation.greeting
}
Then {
assert_equal "Hello, David!",@salutation.greeting
}
end
test_that "greeting works for no first name" do
Given :english_salutation_for,male_with_no_first_name("Copeland")
When {
@greeting = @salutation.greeting
}
Then {
assert_equal "Hello, Mr. Copeland!",@salutation.greeting
}
end
private
def male_with_first_name(first_name)
Person.new(first_name,any_string,:male)
end
def male_with_no_first_name(last_name)
Person.new(nil,last_name,:male)
end
def english_salutation_for(person)
@salutation = Salutation.new(person,Language.new("English","en"))
end
end
=== Why Any instead of Faker?
Faker is used by Any under the covers, but Faker has two problems:
* We aren't _faking_ values, we're using _arbitrary_ values. There's a difference semantically, even if the mechanics are the same
* Faker requires too much typing to get arbitrary values. I'd rather type +any_string+ than Faker::Lorem.words(1).join(' ')
=== What about Factory Girl?
Again, FactoryGirl goes through metaprogramming hoops to do something we can already do in Ruby: call methods. Factory Girl also places factories in global scope, making tests more brittle. You either have a ton of tests depending on the same factory or you have test-specific factories, all in global scope. It's just simpler and more maintainable to use methods and modules for this. To re-use "factories" produced by simple methods, just put them in a module.
Further, the +Any+ module is extensible, in that you can do stuff like any Person, but you can, and should, just use methods. Any helps out with primitives that we tend to use a lot: numbers and strings. It's just simpler and, with less moving parts, more predictable. This means you spend more time on your tests than on your test infrastructure.
=== Any uses random numbers and strings. Tests aren't repeatable!
You can make them repeatable by explicitly setting the random seed to a literal value. Also, including Any will record
the random seed used and output it. You can then set +RANDOM_SEED+ in the environment to re-run he tests using that seed.
Keep in mind that if _any_ value will work, random values shouldn't be a problem.
=== What about not using the base class?
To use Any on its own:
require 'clean_test/any'
class MyTest < Test::Unit::TestCase
include Clean::Test::Any
end
To use GivenWhenThen on its own:
require 'clean_test/given_when_then'
class MyTest < Test::Unit::TestCase
include Clean::Test::GivenWhenThen
end
To use TestThat on its own:
require 'clean_test/test_that'
class MyTest < Test::Unit::TestCase
include Clean::Test::TestThat
end
clean-test-1.0.0/.travis.yml 0000644 0001750 0001750 00000000226 13017326460 014606 0 ustar micah micah notifications:
email:
on_success: always
script: 'bundle exec rake'
rvm:
- 1.9.2
- 1.9.3
- 1.8.7
- ree
- ruby-head
- rbx
- jruby
clean-test-1.0.0/clean_test.gemspec 0000644 0001750 0001750 00000002140 13017326460 016160 0 ustar micah micah # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "clean_test/version"
Gem::Specification.new do |s|
s.name = "clean_test"
s.version = Clean::Test::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["David Copeland"]
s.email = ["davetron5000@gmail.com"]
s.homepage = ""
s.summary = %q{Clean up your Test::Unit tests}
s.description = %q{You can easily make your plain Ruby Test::Unit test cases clean and clear with Given/When/Then, placeholder values, and textual descriptions without resorting to metaprogramming or complex frameworks. Use as much or as little as you like}
s.rubyforge_project = "clean_test"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.add_dependency("faker")
s.add_development_dependency("rdoc")
s.add_development_dependency("sdoc")
s.add_development_dependency("rake")
s.add_development_dependency("simplecov")
end
clean-test-1.0.0/Gemfile 0000644 0001750 0001750 00000000046 13017326460 013770 0 ustar micah micah source "http://rubygems.org"
gemspec
clean-test-1.0.0/.rvmrc 0000644 0001750 0001750 00000000042 13017326460 013623 0 ustar micah micah rvm use 1.9.3@clean_test --create
clean-test-1.0.0/Rakefile 0000644 0001750 0001750 00000003532 13017326460 014145 0 ustar micah micah require 'bundler'
require 'rake/clean'
require 'rake/testtask'
require 'sdoc'
include Rake::DSL
Bundler::GemHelper.install_tasks
desc 'run tests'
Rake::TestTask.new do |t|
t.libs << "lib"
t.libs << "test"
t.ruby_opts << "-rrubygems"
t.test_files = FileList['test/bootstrap.rb','test/test_*.rb']
end
desc 'build rdoc'
task :rdoc => [:build_rdoc, :hack_css]
RDoc::Task.new(:build_rdoc) do |rd|
rd.main = "README.rdoc"
rd.options << '-f' << 'sdoc'
rd.template = 'direct'
rd.rdoc_files.include("README.rdoc","lib/**/*.rb","bin/**/*")
rd.title = 'Clean Test - make your Test::Unit test cases clean and readable'
rd.markup = 'tomdoc'
end
CLOBBER << 'html'
FONT_FIX = {
"0.82em" => "16px",
"0.833em" => "16px",
"0.85em" => "16px",
"1.15em" => "20px",
"1.1em" => "20px",
"1.2em" => "20px",
"1.4em" => "24px",
"1.5em" => "24px",
"1.6em" => "32px",
"1em" => "16px",
"2.1em" => "38px",
}
task :hack_css do
maincss = File.open('html/css/main.css').readlines
File.open('html/css/main.css','w') do |file|
file.puts '@import url(https://fonts.googleapis.com/css?family=Lato:300italic,700italic,300,700);'
maincss.each do |line|
if line.strip == 'font-family: "Helvetica Neue", Arial, sans-serif;'
file.puts 'font-family: Lato, "Helvetica Neue", Arial, sans-serif;'
elsif line.strip == 'font-family: monospace;'
file.puts 'font-family: Monaco, monospace;'
elsif line =~ /^pre\s*$/
file.puts "pre {
font-family: Monaco, monospace;
margin-bottom: 1em;
}
pre.original"
elsif line =~ /^\s*font-size:\s*(.*)\s*;/
if FONT_FIX[$1]
file.puts "font-size: #{FONT_FIX[$1]};"
else
file.puts line.chomp
end
else
file.puts line.chomp
end
end
end
end
CLOBBER << 'coverage'
task :default => :test