Skip to content

Commit

Permalink
Added a should_fail macro to help test failure scenarios in the cor…
Browse files Browse the repository at this point in the history
…e shoulda tests
  • Loading branch information
rmm5t committed Sep 15, 2008
1 parent 2d2c1a4 commit cfd8c7e
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 4 deletions.
34 changes: 34 additions & 0 deletions 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
10 changes: 6 additions & 4 deletions test/test_helper.rb
Expand Up @@ -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")

Expand All @@ -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'
4 changes: 4 additions & 0 deletions test/unit/user_test.rb
Expand Up @@ -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

0 comments on commit cfd8c7e

Please sign in to comment.