therealadam (owner)

Fork Of

Revisions

gist: 181451 Download_button fork
public
Public Clone URL: git://gist.github.com/181451.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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 !@empty.new.respond_to?(:name=)
    end
    
    should 'not add validations from one subclass to another subclass' do
      e = @empty.new
      assert e.valid?
    end
    
  end
  
end