├── .gitignore ├── .travis.yml ├── CODE_OF_CONDUCT.md ├── Gemfile ├── LICENSE.txt ├── README.md ├── Rakefile ├── bin ├── console └── setup ├── lib ├── query_delegator.rb └── query_delegator │ ├── be.rb │ ├── memory_fetching.rb │ ├── respond_or_none.rb │ └── version.rb ├── query_delegator.gemspec └── test ├── query_delegator ├── be_test.rb └── memory_fetching_test.rb ├── query_delegator_test.rb └── test_helper.rb /.gitignore: -------------------------------------------------------------------------------- 1 | /.bundle/ 2 | /.yardoc 3 | /_yardoc/ 4 | /coverage/ 5 | /doc/ 6 | /pkg/ 7 | /spec/reports/ 8 | /tmp/ 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | --- 2 | sudo: false 3 | language: ruby 4 | cache: bundler 5 | rvm: 6 | - 2.5 7 | - 2.6 8 | - 2.7 9 | - ruby-head 10 | before_install: gem install bundler 11 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at ritchie@richorelse.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | git_source(:github) {|repo_name| "https://github.com/#{repo_name}" } 4 | 5 | # Specify your gem's dependencies in query_delegator.gemspec 6 | gemspec 7 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2021 Ritchie Paul Buitre 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # QueryDelegator 2 | 3 | Write composable and table agnostic query objects for Active Record scopes. Move query code from `ActiveRecord` models into query objects, because database query code do not belong in the model. 4 | 5 | ## Installation 6 | 7 | QueryDelegator works with Rails 5.1.7 onwards. Add this line to your application's Gemfile: 8 | 9 | ```ruby 10 | gem 'query_delegator' 11 | ``` 12 | 13 | And then execute: 14 | 15 | $ bundle 16 | 17 | Or install it yourself as: 18 | 19 | $ gem install query_delegator 20 | 21 | ## Usage 22 | 23 | Query objects inherit from `QueryDelegator` class, they typically live under `app/queries` directory. 24 | Naming convention suggests adding a `Query` suffix to query object class names. 25 | Alternatively prefixing class names with words like `By` is shorter and reads more naturally. 26 | 27 | ```ruby 28 | class ByEmail < QueryDelegator 29 | def call(email) 30 | at(email).first 31 | end 32 | 33 | def at(email) 34 | where(email: email.to_s.downcase) 35 | end 36 | 37 | def be(email) 38 | return all unless email.blank? 39 | 40 | at email 41 | end 42 | end 43 | ``` 44 | 45 | Wrap scopes outside `ActiveRecord` models, by either passing the scope as an argument when instantiating a query object or 46 | by passing the query object class as a block argument to the scope's `then` method, also known as `yield_self`. 47 | 48 | ```ruby 49 | @user = ByEmail.new(User).("john.doe@example.test") 50 | @contacts = @user.contacts.then(&ByEmail).be(params[:email]) 51 | ``` 52 | 53 | You may also wrap scopes inside `ActiveRecord` models, like so: 54 | 55 | ```ruby 56 | class User < ApplicationRecord 57 | has_many :contacts 58 | scope :by_email, ByEmail 59 | end 60 | 61 | class Contact < ApplicationRecord 62 | belong_to :user 63 | scope :by_email, ByEmail 64 | end 65 | 66 | @user = User.by_email.("john.doe@example.test") 67 | @contacts = @user.contacts.by_email.be(params[:email]) 68 | ``` 69 | 70 | ### QueryDelegator::[] 71 | 72 | Delegates Active Record scope to a query object method. 73 | Intended for association and named scopes, it accepts a query object's method name and returns a `Proc`. 74 | 75 | ```ruby 76 | class User < ApplicationRecord 77 | has_many :contacts, ByCreated[:recently] 78 | scope :since, ByCreated[:since] 79 | end 80 | 81 | class ByCreated < QueryDelegator 82 | def recently 83 | order(created_at: :desc) 84 | end 85 | 86 | def since(timestamp) 87 | where table[:created_at].gteq(timestamp) 88 | end 89 | end 90 | 91 | @users = User.since 1.year.ago 92 | ``` 93 | 94 | ### QueryDelegator::Be 95 | 96 | To add the helper method `be`, include this module in your query object class like so: 97 | 98 | ```ruby 99 | class ByPublished < QueryDelegator 100 | include Be 101 | 102 | def be_draft 103 | on nil 104 | end 105 | 106 | def be_published 107 | where.not(published_on: nil) 108 | end 109 | 110 | def on(date) 111 | where(published_on: date) 112 | end 113 | end 114 | ``` 115 | 116 | #### be 117 | 118 | Given a name, method `be` invokes another method prefixed with `be_`, otherwise 119 | returns `none` by default or 120 | returns `all` given a blank name. 121 | 122 | ```ruby 123 | @books = @author.books.then(&ByPublished) 124 | @books.be(['draft']) # returns books without publish date 125 | @books.be(:published) # returns books with publish date 126 | @books.be('unknown') # returns none 127 | @books.be(nil) # returns all books 128 | ``` 129 | 130 | ### QueryDelegator::MemoryFetching 131 | 132 | Provides convenient methods intended to retrieve loaded records from memory, 133 | instead of running queries from the database. 134 | Include this module in your query object classes like so: 135 | 136 | ```ruby 137 | class ByColor < QueryDelegator 138 | include MemoryFetching 139 | 140 | def fetch_by_color(color) 141 | fetch -> { |by| by.color == color } 142 | end 143 | end 144 | 145 | ByEmail.include QueryDelegator::MemoryFetching 146 | ``` 147 | 148 | #### fetch 149 | 150 | This helper method retrieves the first record that meets the condition, otherwise 151 | returns either the given block value or the optional default value which is `nil`. 152 | 153 | ```ruby 154 | @vehicles = Vehicle.then(&ByColor) 155 | @vehicles.fetch_by_color 'red' # returns a red Vehicle record 156 | @vehicles.fetch(-> v { v.color == 'gold'} # returns nil 157 | @vehicles.fetch(proc { |v| v.color == 'gold'}, NoVehicle) # returns NoVehicle 158 | @vehicles.fetch(proc { |v| v.color == 'gold'}) { NoVehicle } # returns NoVehicle 159 | @vehicles.fetch(Car) # returns a Car record 160 | ``` 161 | 162 | #### fetch_or_new 163 | 164 | This method also [fetches](#fetch) a record that meets the condition, otherwise loads a new record with `Hash` from the argument condition. 165 | Given a block, it instead fetches a record that meets the block condition. 166 | 167 | ```ruby 168 | class HasEmailOrPhone < SimpleDelegator 169 | def ===(contact) 170 | contact.email == email || contact.phone == phone 171 | end 172 | 173 | def to_h 174 | { full_name: full_name, email: email, phone: phone } 175 | end 176 | end 177 | 178 | @user_contacts = ByEmail.new(@user.contacts) 179 | 180 | # Returns a Contact with the same customer name or email. 181 | @customer_contact = @user_contacts.fetch_or_new(HasEmailOrPhone[@customer]) 182 | 183 | # Either fetch primary Contact or load a new Contact with the specified email. 184 | @primary_contact = @user_contacts.fetch_or_new(email: "john.doe@example.test", &:primary?) 185 | ``` 186 | 187 | ## Development 188 | 189 | After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. 190 | 191 | To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). 192 | 193 | ## Contributing 194 | 195 | Bug reports and pull requests are welcome on GitHub at https://github.com/RichOrElse/query_delegator. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct. 196 | 197 | ## License 198 | 199 | The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). 200 | 201 | ## Code of Conduct 202 | 203 | Everyone interacting in the QueryDelegator project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/RichOrElse/query_delegator/blob/master/CODE_OF_CONDUCT.md). 204 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require "bundler/gem_tasks" 2 | require "rake/testtask" 3 | 4 | Rake::TestTask.new(:test) do |t| 5 | t.libs << "test" 6 | t.libs << "lib" 7 | t.test_files = FileList["test/**/*_test.rb"] 8 | end 9 | 10 | task :default => :test 11 | -------------------------------------------------------------------------------- /bin/console: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | require "bundler/setup" 4 | require "query_delegator" 5 | 6 | # You can add fixtures and/or initialization code here to make experimenting 7 | # with your gem easier. You can also use a different console, if you like. 8 | 9 | # (If you use this, don't forget to add pry to your Gemfile!) 10 | # require "pry" 11 | # Pry.start 12 | 13 | require "irb" 14 | IRB.start(__FILE__) 15 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | IFS=$'\n\t' 4 | set -vx 5 | 6 | bundle install 7 | 8 | # Do any other automated setup that you need to do here 9 | -------------------------------------------------------------------------------- /lib/query_delegator.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/module/delegation" 2 | require "active_support/core_ext/object" 3 | require "query_delegator/version" 4 | require "query_delegator/memory_fetching" 5 | require "query_delegator/be" 6 | 7 | class QueryDelegator 8 | delegate_missing_to :@current_scope 9 | 10 | def initialize(relation) 11 | @current_scope = relation.all 12 | end 13 | 14 | class << self 15 | # Returns a Proc which wraps an ActiveRecord scope in a new query object instance. 16 | def to_proc 17 | delegator = self 18 | 19 | proc do |*args| 20 | if equal? delegator 21 | new(*args) 22 | else 23 | delegator.(self, *args) 24 | end 25 | end 26 | end 27 | 28 | # Returns a Proc which delegates an ActiveRecord model scope to query object instance method. 29 | def [](delegating) 30 | delegator = self 31 | 32 | if public_instance_method(delegating).arity.zero? 33 | proc do 34 | delegator.new(self).public_send delegating 35 | end 36 | else 37 | proc do |*options| 38 | delegator.new(self).public_send delegating, *options 39 | end 40 | end 41 | end 42 | 43 | alias_method :call, :new 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /lib/query_delegator/be.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | require_relative 'respond_or_none' 3 | 4 | class QueryDelegator 5 | module Be 6 | using RespondOrNone 7 | 8 | # Invokes method name prefixed with +be_+, othewise 9 | # returns +all+ given a blank name or 10 | # returns +none+ when method is unrecognized. 11 | def be(name, *args, &blk) 12 | return all if name.blank? 13 | 14 | underscored = name.to_s.strip.underscore 15 | .gsub(/[^0-9a-z _]/i, '') 16 | .gsub(/\s+/, '_') 17 | 18 | respond_to("be_#{underscored}", *args, &blk) 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /lib/query_delegator/memory_fetching.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class QueryDelegator 4 | module MemoryFetching 5 | # Returns the first record that meets the +condition+, otherwise 6 | # returns the given +block value+ or 7 | # returns +nil+ by default unless a second argument is specified. 8 | def fetch(condition, default_value = nil) 9 | grep(condition) { |found| return found } 10 | return yield condition if defined? yield 11 | 12 | default_value 13 | end 14 | 15 | # Returns the first record that meets either the +block condition+ if given or the argument +condition+, otherwise 16 | # returns a new record with Hash from the argument +condition+. 17 | def fetch_or_new(condition, &block_condition) 18 | fetch(block_condition || condition) { new(condition.to_h) } 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /lib/query_delegator/respond_or_none.rb: -------------------------------------------------------------------------------- 1 | class QueryDelegator 2 | module RespondOrNone 3 | # Invokes a public method, otherwise 4 | # returns +none+ when method is unrecognized 5 | def respond_to(method_name, *args, &blk) 6 | return none unless respond_to?(method_name) 7 | 8 | public_send(method_name, *args, &blk) 9 | end 10 | 11 | refine ::Object do 12 | include RespondOrNone 13 | end 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /lib/query_delegator/version.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class QueryDelegator 4 | VERSION = "1.0.0" 5 | end 6 | -------------------------------------------------------------------------------- /query_delegator.gemspec: -------------------------------------------------------------------------------- 1 | 2 | lib = File.expand_path("../lib", __FILE__) 3 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) 4 | require "query_delegator/version" 5 | 6 | Gem::Specification.new do |spec| 7 | spec.name = "query_delegator" 8 | spec.version = QueryDelegator::VERSION 9 | spec.authors = ["Ritchie Paul Buitre"] 10 | spec.email = ["ritchie@richorelse.com"] 11 | 12 | spec.summary = "Write composable and table agnostic query objects for Active Record scopes." 13 | spec.description = "Move query code from ActiveRecord models into query objects, because database query code do not belong in the model." 14 | spec.homepage = "https://github.com/RichOrElse/query_delegator" 15 | spec.license = "MIT" 16 | 17 | # Specify which files should be added to the gem when it is released. 18 | # The `git ls-files -z` loads the files in the RubyGem that have been added into git. 19 | spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do 20 | `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } 21 | end 22 | spec.bindir = "exe" 23 | spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } 24 | spec.require_paths = ["lib"] 25 | 26 | spec.required_ruby_version = ">= 2.2.2" 27 | spec.add_runtime_dependency "activesupport", ">= 5.1.7" 28 | 29 | spec.add_development_dependency "bundler", ">= 1.17" 30 | spec.add_development_dependency "rake", ">= 10.0" 31 | spec.add_development_dependency "minitest", "~> 5.1" 32 | end 33 | -------------------------------------------------------------------------------- /test/query_delegator/be_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | require "test_helper" 3 | 4 | describe QueryDelegator::Be do 5 | subject { subclass.new OpenStruct.new(all: scope) } 6 | let(:scope) { OpenStruct.new(none: [], all: 1..9) } 7 | let(:subclass) { Class.new(QueryDelegator).include QueryDelegator::Be } 8 | 9 | describe "#be" do 10 | before do 11 | def subject.be_matching_method; object_id end 12 | end 13 | 14 | describe "with matching method" do 15 | let(:returns) { subject.be('matching method') } 16 | it { _(returns).must_equal subject.be_matching_method } 17 | end 18 | 19 | describe "without matching method" do 20 | let(:returns) { subject.be('something else') } 21 | it { _(returns).must_equal scope.none } 22 | end 23 | 24 | describe "with blank" do 25 | let(:returns) { subject.be('') } 26 | it { _(returns).must_equal scope.all } 27 | end 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /test/query_delegator/memory_fetching_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | require "test_helper" 3 | 4 | describe QueryDelegator::MemoryFetching do 5 | subject { subclass.new(OpenStruct.new(all: all)) } 6 | let(:subclass) { Class.new(QueryDelegator).include QueryDelegator::MemoryFetching } 7 | 8 | let(:all) { [2,3,4,5] } 9 | 10 | describe "fetch" do 11 | let(:returns) { subject.fetch(condition) } 12 | 13 | describe "with matching condition" do 14 | let(:condition) { proc(&:odd?) } 15 | it { _(returns).must_equal all.grep(condition).first } 16 | end 17 | 18 | describe "without matching condition" do 19 | let(:condition) { 100 } 20 | it { _(returns).must_be_nil } 21 | 22 | describe "and with default value" do 23 | let(:returns) { subject.fetch(condition, :default_value) } 24 | it { _(returns).must_equal :default_value } 25 | end 26 | 27 | describe "given a block" do 28 | let(:returns) { subject.fetch(condition) { :block_value } } 29 | it { _(returns).must_equal :block_value } 30 | end 31 | end 32 | end 33 | 34 | describe "#fetch_or_new" do 35 | let(:returns) { subject.fetch_or_new(condition, &given_block) } 36 | let(:given_block) { nil } 37 | 38 | before do 39 | def all.new(*) object_id end 40 | end 41 | 42 | describe "without matching condition" do 43 | let(:condition) { { name: 'no match' } } 44 | it { _(returns).must_equal all.new } 45 | 46 | describe "but with given block" do 47 | let(:given_block) { proc(&:even?) } 48 | it { _(returns).must_equal all.grep(given_block).first } 49 | end 50 | end 51 | 52 | describe "with matching condition" do 53 | let(:condition) { 3 } 54 | it { _(returns).must_equal all.grep(condition).first } 55 | end 56 | end 57 | end 58 | -------------------------------------------------------------------------------- /test/query_delegator_test.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | describe QueryDelegator do 4 | let(:invoked_call) { MiniTest::Mock.new } 5 | let(:invoked_new) { MiniTest::Mock.new } 6 | let(:instance) { @subclass.new(@object) } 7 | 8 | before do 9 | @object = OpenStruct.new(all: []) 10 | @subclass = Class.new(QueryDelegator) do 11 | def with_owner(owner) 12 | 'with owner' 13 | end 14 | 15 | def without_owner 16 | 'without owner' 17 | end 18 | end 19 | end 20 | 21 | describe "to_proc" do 22 | describe "when yielded an object" do 23 | subject { [@object].map(&@subclass) } 24 | 25 | it "must invoke new with the object" do 26 | invoked_new.expect :call, instance, [@object] 27 | @subclass.stub(:new, invoked_new) { subject } 28 | invoked_new.verify 29 | end 30 | end 31 | 32 | describe "when executed within the context of an object" do 33 | subject { @object.instance_exec(:next, :last, &@subclass) } 34 | 35 | it "must invoke call with the object and arguments" do 36 | invoked_call.expect :call, instance, [@object, :next, :last] 37 | @subclass.stub(:call, invoked_call) { subject } 38 | invoked_call.verify 39 | end 40 | end 41 | end 42 | 43 | describe "[]" do 44 | it "only accepts an instance method name" do 45 | assert_raises(NameError) { @subclass[:unknown] } 46 | assert_raises(ArgumentError) { @subclass[] } 47 | assert_raises(ArgumentError) { @subclass[:with_owner, :without_owner] } 48 | end 49 | 50 | it "returns a proc" do 51 | _(@subclass[:with_owner]).must_be_kind_of Proc 52 | end 53 | 54 | describe "when executed within the context of an object" do 55 | before { invoked_new.expect :call, instance, [@object] } 56 | after { invoked_new.verify } 57 | 58 | describe "with argument" do 59 | subject { @object.instance_exec(:owner, &@subclass[:with_owner]) } 60 | 61 | it "delegates method call to an instance" do 62 | @subclass.stub(:new, invoked_new) do 63 | _(subject).must_equal 'with owner' 64 | end 65 | end 66 | end 67 | 68 | describe "without argument" do 69 | subject { @object.instance_exec(&@subclass[:without_owner]) } 70 | 71 | it "delegates method call to an instance" do 72 | @subclass.stub(:new, invoked_new) do 73 | _(subject).must_equal 'without owner' 74 | end 75 | end 76 | end 77 | end 78 | end 79 | end 80 | -------------------------------------------------------------------------------- /test/test_helper.rb: -------------------------------------------------------------------------------- 1 | $LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) 2 | require "query_delegator" 3 | 4 | require "minitest/autorun" 5 | --------------------------------------------------------------------------------