From bc11e9f3008bc0c11a789b29cc034bf9e199605d Mon Sep 17 00:00:00 2001 From: Rodrigo Flores Date: Tue, 21 Feb 2012 10:31:38 -0200 Subject: [PATCH] One exception to rule them all --- lib/devise/models.rb | 8 +++++++- test/models_test.rb | 21 ++++++++++++++++++--- test/support/assertions.rb | 8 ++++++++ 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/lib/devise/models.rb b/lib/devise/models.rb index cfaf2c8c..369e7f54 100644 --- a/lib/devise/models.rb +++ b/lib/devise/models.rb @@ -43,13 +43,19 @@ module Devise end def self.check_fields!(klass) + failed_attributes = [] + klass.devise_modules.each do |mod| instance = klass.new const_get(mod.to_s.classify).required_fields(klass).each do |field| - fail Devise::Models::MissingAttribute unless instance.respond_to?(field) + failed_attributes << field unless instance.respond_to?(field) end end + + if failed_attributes.any? + fail Devise::Models::MissingAttribute, "The following attributes are missing on your model: #{failed_attributes.join(", ")}" + end end # Include the chosen devise modules in your model: diff --git a/test/models_test.rb b/test/models_test.rb index e7b87a7a..21b640e2 100644 --- a/test/models_test.rb +++ b/test/models_test.rb @@ -126,7 +126,7 @@ class CheckFieldsTest < ActiveSupport::TestCase end end - test 'raises Devise::Models::MissingAtrribute if the class doesn\'t respond_to one of the attributes' do + test 'raises Devise::Models::MissingAtrribute and shows the missing attribute if the class doesn\'t respond_to one of the attributes' do Clown = Class.new do extend Devise::Models @@ -138,8 +138,23 @@ class CheckFieldsTest < ActiveSupport::TestCase attr_accessor :encrypted_password end - assert_raise Devise::Models::MissingAttribute do + assert_raise_with_message Devise::Models::MissingAttribute, "The following attributes are missing on your model: email" do Devise::Models.check_fields!(Clown) end end -end \ No newline at end of file + + test 'raises Devise::Models::MissingAtrribute with all the missing attributes if there is more than one' do + Magician = Class.new do + extend Devise::Models + + def self.before_validation(instance) + end + + devise :database_authenticatable + end + + exception = assert_raise_with_message Devise::Models::MissingAttribute, "The following attributes are missing on your model: encrypted_password, email" do + Devise::Models.check_fields!(Magician) + end + end +end diff --git a/test/support/assertions.rb b/test/support/assertions.rb index b8d104a3..95de3448 100644 --- a/test/support/assertions.rb +++ b/test/support/assertions.rb @@ -32,4 +32,12 @@ class ActiveSupport::TestCase assert !element.nil?, "the arrays doesn't have the same content" end end + + def assert_raise_with_message(exception_klass, message) + exception = assert_raise exception_klass do + yield + end + + assert_equal exception.message, message, "The expected message was #{message} but your exception throwed #{exception.message}" + end end