Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added a `should_fail` macro to help test failure scenarios in the cor…

…e shoulda tests
  • Loading branch information...
commit cfd8c7e305526813c77c176d9b36e561fa0ccb98 1 parent 2d2c1a4
@rmm5t rmm5t authored
View
34 test/fail_macros.rb
@@ -0,0 +1,34 @@
+module Thoughtbot
+ module Shoulda
+ class << self
+ attr_accessor :expected_exceptions
+ end
+
+ # Enables the core shoulda test suite to test for failure scenarios. For
+ # example, to ensure that a set of test macros should fail, do this:
+ #
+ # should_fail do
+ # should_require_attributes :comments
+ # should_protect_attributes :name
+ # end
+ def should_fail(&block)
+ context "should fail when trying to run:" do
+ Shoulda.expected_exceptions = [Test::Unit::AssertionFailedError]
+ yield block
+ Shoulda.expected_exceptions = nil
+ end
+ end
+
+ class Context
+ # alias_method_chain hack to allow the should_fail macro to work
+ def should_with_failure_scenario(name, options = {}, &block)
+ if Shoulda.expected_exceptions
+ expected_exceptions = Shoulda.expected_exceptions
+ failure_block = lambda { assert_raise(*expected_exceptions, &block.bind(self)) }
+ end
+ should_without_failure_scenario(name, options, &(failure_block || block))
+ end
+ alias_method_chain :should, :failure_scenario
+ end
+ end
+end
View
10 test/test_helper.rb
@@ -5,15 +5,15 @@
rails_root = File.dirname(__FILE__) + '/rails_root'
require "#{rails_root}/config/environment.rb"
-
+
# Load the testing framework
require 'test_help'
silence_warnings { RAILS_ENV = ENV['RAILS_ENV'] }
-
+
# Run the migrations
ActiveRecord::Migration.verbose = false
ActiveRecord::Migrator.migrate("#{RAILS_ROOT}/db/migrate")
-
+
# Setup the fixtures path
Test::Unit::TestCase.fixture_path = File.join(File.dirname(__FILE__), "fixtures")
@@ -25,7 +25,9 @@ def create_fixtures(*table_names)
Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names)
end
end
-
+
self.use_transactional_fixtures = false
self.use_instantiated_fixtures = false
end
+
+require 'test/fail_macros'
View
4 test/unit/user_test.rb
@@ -44,4 +44,8 @@ class UserTest < Test::Unit::TestCase
should_only_allow_numeric_values_for :ssn
should_have_readonly_attributes :name
+
+ should_fail do
+ should_protect_attributes :name, :age
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.