Skip to content

Instantly share code, notes, and snippets.

@Joseworks
Forked from antillas21/spec.rb
Created April 22, 2024 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Joseworks/516db28d8e2fbfc967631bdec6d55469 to your computer and use it in GitHub Desktop.
Save Joseworks/516db28d8e2fbfc967631bdec6d55469 to your computer and use it in GitHub Desktop.
Stubbing an ActiveRecord::Relation object
# 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 }
@Joseworks
Copy link
Author

Or dolet(:rate_agreements) { Prosopite.pause { create_list(:rate_agreement, 3) } }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment