forked from instructure/canvas-lms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rspec_mock_extensions.rb
74 lines (66 loc) · 2.56 KB
/
rspec_mock_extensions.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
# frozen_string_literal: true
#
# Copyright (C) 2011 - present Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
# allows setting up mocks/stubs that will be automatically applied any time
# this AR instance is instantiated, through find or whatever
# the record must be saved before calling any_instantiation, so that it has an id
module RspecMockAnyInstantiation
module ClassMethods
def reset_any_instantiation!
@@any_instantiation = {}
end
def add_any_instantiation(ar_obj)
raise(ArgumentError, "need to save first") if ar_obj.new_record?
@@any_instantiation[[ar_obj.class.base_class, ar_obj.id]] = ar_obj
# calling any_instantiation is likely to be because you're stubbing it,
# and to later be cached inadvertently from code that *thinks* it
# has a non-stubbed object. So let it dump, but not load (i.e.
# the MemoryStore and NilStore dumps that are just for testing,
# but just discard the result of dump)
def ar_obj.marshal_dump
nil
end
# no marshal_load; will raise an exception on load
ar_obj
end
def instantiate(record, column_types = {}, &block)
if (obj = @@any_instantiation[[base_class, record["id"].to_i]])
obj
else
super
end
end
def instantiate_instance_of(klass, record, column_types = {}, &block)
if (obj = @@any_instantiation[[klass, record["id"].to_i]])
obj
else
super
end
end
end
def allow_any_instantiation_of(ar_object)
ActiveRecord::Base.add_any_instantiation(ar_object)
allow(ar_object)
end
def expect_any_instantiation_of(ar_object)
ActiveRecord::Base.add_any_instantiation(ar_object)
expect(ar_object) # rubocop:disable RSpec/VoidExpect we return the expectation object to the caller
end
end
ActiveRecord::Base.singleton_class.prepend(RspecMockAnyInstantiation::ClassMethods)
RSpec::Mocks::ExampleMethods.include(RspecMockAnyInstantiation)
ActiveRecord::Base.reset_any_instantiation!