[rspec-users] Q: object.id is deprecated. How to mock?

Pat Maddox pergesu at gmail.com
Tue Nov 25 17:31:10 EST 2008

"s.ross" <cwdinfo at gmail.com> writes:

> 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:
> @post[:body_text]
> 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
> return self[:id].
> Questions:
> 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.
> Thanks,
> Steve
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users

I came across this today when I used stub_model.  I hadn't given it an
explicit ID so I got that warning.  So if that's why you're
encountering, just do something like
@post = stub_model(:id => 123)

As others have said though, only Object#id is deprecated.  AR::Base#id
is still valid.


More information about the rspec-users mailing list