[rspec-users] Q: object.id is deprecated. How to mock?
cwdinfo at gmail.com
Tue Nov 25 14:04:25 EST 2008
In Rails, the primary key, by default 'id', is used all over the
place. However, Ruby now deprecates the use of constructs like:
@post = Post.find(:first)
@post_id = @post.id
I buy the rationale, as the Object#id is something of a reserved
method. However, changing all references to use [:id], while seemingly
the correct approach, also has the unwanted side-effect of breaking
every mock created using mock_model that references the id that way.
Sure, I can go in and stub  to return self[:id] for each mock
object, but that ActiveRecord objects behave more as a hash than as an
object (IMO), so there are things like:
peppered throughout the codebase, and a big hammer like a stub of the
() method would also break specs. So the conundrum is how to make
mock_model respond only to the () method with an argument of :id to
1. Is there something bogus in my assumption that using @post[:id] is
preferred to @post.id?
2. Has anyone solved this problem and if so what worked?
BTW: I am aware that :to_param returns the id, but it seems counter-
intuitive to read code that takes advantage of this quirk.
More information about the rspec-users