diff --git a/lib/shoulda/matchers/active_record/validate_presence_of_matcher.rb b/lib/shoulda/matchers/active_record/validate_presence_of_matcher.rb index e792461a..088a1cd8 100644 --- a/lib/shoulda/matchers/active_record/validate_presence_of_matcher.rb +++ b/lib/shoulda/matchers/active_record/validate_presence_of_matcher.rb @@ -47,7 +47,8 @@ module Shoulda # :nodoc: end def collection? - if reflection = @subject.class.reflect_on_association(@attribute) + if @subject.class.respond_to?(:reflect_on_association) && + reflection = @subject.class.reflect_on_association(@attribute) [:has_many, :has_and_belongs_to_many].include?(reflection.macro) else false diff --git a/spec/shoulda/active_record/validate_presence_of_matcher_spec.rb b/spec/shoulda/active_record/validate_presence_of_matcher_spec.rb index 9439f9cd..7fd6f792 100644 --- a/spec/shoulda/active_record/validate_presence_of_matcher_spec.rb +++ b/spec/shoulda/active_record/validate_presence_of_matcher_spec.rb @@ -19,6 +19,23 @@ describe Shoulda::Matchers::ActiveRecord::ValidatePresenceOfMatcher do end end + context "a required attribute on a class using ActiveModel::Validations" do + before do + define_active_model_class("Example", :accessors => [:attr]) do + validates_presence_of :attr + end + @model = Example.new + end + + it "should require a value" do + @model.should validate_presence_of(:attr) + end + + it "should not override the default message with a blank" do + @model.should validate_presence_of(:attr).with_message(nil) + end + end + context "an optional attribute" do before do @model = define_model(:example, :attr => :string).new @@ -29,6 +46,16 @@ describe Shoulda::Matchers::ActiveRecord::ValidatePresenceOfMatcher do end end + context "an optional attribute on a class using ActiveModel::Validations" do + before do + @model = define_active_model_class("Example", :accessors => [:attr]).new + end + + it "should not require a value" do + @model.should_not validate_presence_of(:attr) + end + end + context "a required has_many association" do before do define_model :child diff --git a/spec/support/model_builder.rb b/spec/support/model_builder.rb index 3c13b241..50a794a6 100644 --- a/spec/support/model_builder.rb +++ b/spec/support/model_builder.rb @@ -42,6 +42,18 @@ module ModelBuilder define_constant(class_name, ActiveRecord::Base, &block) end + def define_active_model_class(class_name, options = {}, &block) + define_constant(class_name, Object) do + include ActiveModel::Validations + + options[:accessors].each do |column| + attr_accessor column.to_sym + end + + class_eval(&block) if block_given? + end + end + def define_model(name, columns = {}, &block) class_name = name.to_s.pluralize.classify table_name = class_name.tableize