Using OpenStruct as mock for ActiveRecord
As you may have noticed OpenStruct#id always returns the object id of the OpenStruct instance, even when you set id.
>> o = OpenStruct.new :id => 2
=> #<OpenStruct id=2>
>> o.id
(irb):4: warning: Object#id will be deprecated; use Object#object_id
=> 9850940
Fortunately there is a simple way around this.
OpenStruct.__send__(:define_method, :id) { @table[:id] }
Now OpenStruct behaves like we want.
>> o.id
=> 2
Note that hash and object_id still work fine. You probably want to keep in mind that we’ve redefined the default OpenStruct behaviour and it might cause problems elsewhere.
Comments
Add your comment
In order to fight spam on this blog, posting comments from a browser without javascript is currently not supported.
Subscribe
Chris about 3 hours later: (delete)
I usually throw this little line into my test_helper:
OpenStruct.class_eval { undef :id, :type } ¶