/
stub.rb
81 lines (67 loc) · 1.97 KB
/
stub.rb
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
module FactoryGirl
class Proxy
class Stub < Proxy #:nodoc:
@@next_id = 1000
def initialize(klass)
@instance = klass.new
@ignored_attributes = {}
@instance.id = next_id
@instance.instance_eval do
def persisted?
!new_record?
end
def new_record?
id.nil?
end
def save(*args)
raise "stubbed models are not allowed to access the database"
end
def destroy(*args)
raise "stubbed models are not allowed to access the database"
end
def connection
raise "stubbed models are not allowed to access the database"
end
def reload
raise "stubbed models are not allowed to access the database"
end
def update_attribute(*args)
raise "stubbed models are not allowed to access the database"
end
end
end
def next_id
@@next_id += 1
end
def get(attribute)
if @ignored_attributes.has_key?(attribute)
@ignored_attributes[attribute]
else
@instance.send(attribute)
end
end
def set(attribute, value, ignored = false)
if ignored
@ignored_attributes[attribute] = value
else
@instance.send(:"#{attribute}=", value)
end
end
def associate(name, factory_name, overrides)
factory = FactoryGirl.factory_by_name(factory_name)
set(name, factory.run(Proxy::Stub, remove_method(overrides)))
end
def association(factory_name, overrides = {})
factory = FactoryGirl.factory_by_name(factory_name)
factory.run(Proxy::Stub, remove_method(overrides))
end
def remove_method(overrides)
overrides.dup.delete_if {|key, value| key == :method}
end
def result(to_create)
run_callbacks(:after_stub)
@instance
end
end
end
end