Instantly share code, notes, and snippets.

@ka8725 /ar_relation_stub.rb Secret
Last active Nov 27, 2018

What would you like to do?
# Allows to stub a chain of scopes and aggregate functions on a `has_many` association.
# For example, there is `Subscription` `has_many` `users` association and somewhere in the code there is a call
# like ``. This class can be used to stub this association easily so that
# any scope's call in the chain returns the given collection of records and aggregate functions behave like
# `ActiveRecord`'s ones.
# Example:
# ```ruby
# users =, [user1, user], scopes: %i[active verified])
# allow(subscription).to receive(:users).and_return(users)
# ```
# @note If you find some aggregate functions missing feel free to add them.
class ActiveRecordRelationStub
attr_reader :records
alias to_a records
# @param model_klass [ActiveRecord::Base] the stubbing association's class
# @param records [Array] list of records the association holds
# @param scopes [Array] list of stubbed scopes
def initialize(model_klass, records, scopes: [])
@records = records
scopes.each do |scope|
fail NotImplementedError, scope unless model_klass.respond_to?(scope)
define_singleton_method(scope) do
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment