How to completely restart ActiveRecord?

In the RSpec test, I create an entry with several memoizied values.

foo.reload works as expected for the attributes of the object, but memoized is still present.

While it works, completely recreating the object: foo = Foo.find(123) , but in my case, the logic for finding a record is actually more complicated.

What a good, DRY way to completely reload the record and erase all the values ​​you notice?

+6
source share
2 answers

A good way is the one you already have: Completely re-creating the object.

You cannot "reload" memoized object values ​​in any simple "Rails" way, since memoizing attributes are not a Rails or ActiveRecord function. Knows nothing about memoizing methods.

+4
source

You can do this by overriding reload . For example, if you remember using ||= , you can do this:

 class Foo < ActiveRecord::Base def bar @bar ||= rand end def reload @bar = nil super end end 

For paths to reset all instance variables, see Is there a clean API to reset instance variables in 'reload' in ActiveRecord?

If you use memoist gem, you can call flush_cache there.

+1
source

Source: https://habr.com/ru/post/981877/


All Articles