1
0
Fork 0
mirror of https://github.com/thoughtbot/shoulda-matchers.git synced 2022-11-09 12:01:38 -05:00

Support validates_presence_of with a class using ActiveModel::Validations.

This commit is contained in:
Tristan Dunn 2011-01-24 11:19:34 -05:00
parent a2f7eefc66
commit 3daca5b601
3 changed files with 41 additions and 1 deletions

View file

@ -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

View file

@ -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

View file

@ -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