Skip to content

Instantly share code, notes, and snippets.

@antillas21

antillas21/spec.rb

Last active Feb 6, 2019
Embed
What would you like to do?
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 }
@keesbriggs

This comment has been minimized.

Copy link

@keesbriggs keesbriggs commented Dec 6, 2017

Line 6 is missing a square brace.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.