Created
August 11, 2011 22:48
-
-
Save paydro/1140999 to your computer and use it in GitHub Desktop.
Allows #context calls in Rails 3 tests like rspec/minitest spec
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Create a context block like rspec. | |
# | |
# Inspired by: | |
# - MiniTest::Spec | |
# - Chris Wanstrath's https://gist.github.com/25455 | |
# | |
# Examples: | |
# | |
# class UserTest < ActiveSupport::TestCase | |
# context "Auth" do | |
# test "..." do; end | |
# ... | |
# | |
# context "Another context" do | |
# test "..." do; end | |
# ... | |
# end | |
# end | |
# end | |
def self.context(name, &block) | |
name = self.to_s + name.split(/\W+/).map {|s| s.capitalize }.join | |
klass = Object.class_eval "class #{name} < #{self}; end; #{name}" | |
# Remove previous class's test methods | |
klass.public_instance_methods.grep(/^test_/).each do |tname| | |
klass.send :undef_method, tname | |
end | |
# Ensure ActionController::TestCase tests the correct controller | |
if index = self.ancestors.index(ActionController::TestCase) | |
klass.tests self.ancestors[index-1].to_s.sub(/Test$/, '').constantize | |
end | |
klass.class_eval &block | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment