Created
September 5, 2009 16:04
-
-
Save therealadam/181451 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'validatable' | |
module ValidatableForm | |
module ClassMethods | |
def fields | |
@fields ||= [] | |
end | |
def form_fields(*form_fields) | |
return if form_fields.empty? | |
@fields = form_fields | |
attr_accessor *@fields | |
end | |
end | |
module InstanceMethods | |
def initialize(params={}) | |
self.class.fields.each { |a| send("#{a}=", params[a]) } | |
end | |
# used by some of the rails view helpers like form_for | |
def id | |
nil | |
end | |
# used by some of the rails view helpers like form_for | |
def new_record? | |
true | |
end | |
end | |
def self.included(receiver) | |
receiver.extend ClassMethods | |
receiver.send :include, InstanceMethods | |
end | |
end | |
require 'test/unit' | |
require 'shoulda' | |
class TestValidatableForm < Test::Unit::TestCase | |
context 'ValidatableForm' do | |
setup do | |
@contact = Class.new do | |
include Validatable | |
include ValidatableForm | |
form_fields :name, :email, :subject, :comment | |
validates_presence_of :name | |
validates_presence_of :email | |
validates_presence_of :subject | |
validates_presence_of :comment | |
end | |
@empty = Class.new do | |
include Validatable | |
include ValidatableForm | |
end | |
end | |
should 'allow adding fields in one subclass' do | |
assert @contact.new.respond_to?(:name=) | |
end | |
should 'allow adding validations in one subclass' do | |
c = @contact.new(:name => 'Foo') | |
assert !c.valid? | |
end | |
should 'not add fields from one subclass to another subclass' do | |
assert [email protected]_to?(:name=) | |
end | |
should 'not add validations from one subclass to another subclass' do | |
e = @empty.new | |
assert e.valid? | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment