Ruby Object#id warnings and Active Record
-
03-07-2019 - |
Question
We keep seeing warnings like the following when we run our specs:
Object#id will be deprecated; use Object#object_id
The code in question is accessing the id of an ActiveRecord model (which is an attribute on the table, obviously, rather than the object instance ID in the Ruby VM).
Does anyone know how to turn these particular warnings off or somehow avoid them?
Solution
I'm assuming you're doing mocking / stubbing (because you mentioned specs).
In my case, I run into these warnings when I stub an ActiveRecord object and access its ID attribute.
In cases where you expect to access the ID of your ActiveRecord object, I'd recommend you do the following:
mock("MyActiveRecordObject", :id => 1001)
OTHER TIPS
Try using [:id]
instead of .id
When an object is descended from ActiveRecord::Base
, a call to id
goes to AR::B's id
method rather than the deprecated one on Object
.
That warning usually means one of my objects isn't what I think it is.
Your object is not actually an AR object, usually indicating that some data retrieval has failed (Table.find_by_name('nonexistent name')
will return nil
). If all you want to do is shut off the visible warnings, you can turn off whiny_nils
in your config, otherwise do an is_a?
test before trying to access the object's attributes and handle the failure case gracefully.
The object#id warning only happen on regular ruby classes like NilClass. ActiveRecord::Base overrides object#id