Class: Validity::ActiveRecord::Wrapper

Inherits:
Object
  • Object
show all
Includes:
Test::Unit::Assertions
Defined in:
lib/validity/active_record.rb

Instance Method Summary collapse

Constructor Details

#initialize(record) ⇒ Wrapper

Returns a new instance of Wrapper.



12
13
14
# File 'lib/validity/active_record.rb', line 12

def initialize(record)
  @record = record
end

Instance Method Details

#belongs_to(field, target) ⇒ Object



16
17
18
19
20
21
22
23
# File 'lib/validity/active_record.rb', line 16

def belongs_to(field, target)
  clazz = @record.class
  assert_respond_to @record, field, "#{clazz} cannot find associated #{field}"

  one = @record.send(field)
  assert_not_nil one, "#{clazz} does not have associated #{field}"
  assert_equal target, one, "#{field.to_s.capitalize} associated with this #{clazz.to_s.downcase} is not the target #{field}"
end

#delegates(delegated, delegated_to) ⇒ Object



25
26
27
28
29
# File 'lib/validity/active_record.rb', line 25

def delegates(delegated, delegated_to)
  clazz = @record.class
  assert_respond_to @record, delegated, "#{clazz} does not respond to #{delegated}"
  assert_equal delegated_to.send(delegated), @record.send(delegated), "Delegated objects do not match"
end

#field_presence(field) ⇒ Object



31
32
33
34
35
36
37
38
39
40
# File 'lib/validity/active_record.rb', line 31

def field_presence(field)
  # Null out the field to test
  @record.send("#{field}=", nil)

  # Assert the record is invalid and will not save
  clazz = @record.class
  assert !@record.valid?, "#{clazz} is considered valid with nil #{field}"
  assert !@record.save, "#{clazz} saved without #{field} field"
  assert @record.errors[field].any?, "#{clazz} does not have an error on #{field}"
end

#field_uniqueness(field) ⇒ Object



42
43
44
45
46
47
48
49
50
51
# File 'lib/validity/active_record.rb', line 42

def field_uniqueness(field)
  # Create a duplicate of the record
  dup = @record.dup

  # Assert the duplicate is invalid based on the field
  clazz = dup.class
  assert !dup.valid?, "#{clazz} is considered valid with duplicate #{field}"
  assert !dup.save, "#{clazz} saved with a duplicate #{field}"
  assert dup.errors[field].any?, "#{clazz} does not have an error on #{field}"
end

#has_many(field, targets) ⇒ Object



53
54
55
56
57
58
59
60
# File 'lib/validity/active_record.rb', line 53

def has_many(field, targets)
  clazz = @record.class
  assert_respond_to @record, field, "#{clazz} cannot find associated #{field}"

  many = @record.send(field)
  assert !(many.nil? || many.empty?), "#{clazz} does not have associated #{field}"
  assert_equal targets.size, many.size, "#{clazz} does not have #{targets.size} associated #{field}"
end