Skip to content

Commit

Permalink
Support validates_presence_of with a class using ActiveModel::Validat…
Browse files Browse the repository at this point in the history
…ions.
  • Loading branch information
tristandunn committed Jan 24, 2011
1 parent a2f7eef commit 3daca5b
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ def blank_value
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
Expand Down
27 changes: 27 additions & 0 deletions spec/shoulda/active_record/validate_presence_of_matcher_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,23 @@
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
Expand All @@ -29,6 +46,16 @@
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
Expand Down
12 changes: 12 additions & 0 deletions spec/support/model_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,18 @@ def define_model_class(class_name, &block)
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
Expand Down

0 comments on commit 3daca5b

Please sign in to comment.