Last active
April 22, 2024 16:56
-
-
Save antillas21/11232600 to your computer and use it in GitHub Desktop.
Stubbing an ActiveRecord::Relation object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# first we create an empty ActiveRecord::Relation object | |
relation = Model.where(attribute: value) | |
# then we make the relation stub the :[] method | |
# and return whatever values we need | |
relation.stub(:[]).and_return( Model.new({attrs: values})] ) | |
# of course, we can make this too | |
# instead of the step above | |
record = double("Model", :foo => 'bar', :bar => 'baz') | |
relation.stub(:[]).and_return([record]) | |
# last, we make our Model class stub the :where method | |
# and return the relation object we created | |
Model.stub(:where).and_return(relation) | |
# additionally we can have use case specific behavior | |
model_instance.stub(:method_or_scope_that_returns_collection) { relation } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wonder why your code didn't work in my particular case. Could it be related to my call of
relation = original.call(*args, &block)
always returning anil
object?relation.stub(:records)
raisesunknown #stub method for #<ActiveRecord::Associations::CollectionProxy []>
But I found a way out of this, not sure if ideal, though:
Mocking only the
has_many
return was insufficient for my case because I also needed to mock the scope call.record.related_records.scope_of_related_class
Thanks!