Skip to content

Instantly share code, notes, and snippets.

@petitviolet
Created August 16, 2021 12:47
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 petitviolet/9953af0aa561ea49c5e2aa13dd52f2ef to your computer and use it in GitHub Desktop.
Save petitviolet/9953af0aa561ea49c5e2aa13dd52f2ef to your computer and use it in GitHub Desktop.
allow_any_instance_of to count up the number of method calls across different instances
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
gem 'rspec', '~> 3.0'
end
require 'rspec/autorun'
RSpec.describe 'test', type: :model do
class Hoge
def hoge; end
end
describe 'Hoge' do
it 'raise error with exactly matcher' do
expect_any_instance_of(Hoge).to receive(:hoge).exactly(1).times
Hoge.new.hoge
expect { Hoge.new.hoge }.to raise_error(/The message 'hoge' was received by #<Hoge:.+>/)
end
it 'succeeds with giving proc to count up' do
n = 0
allow_any_instance_of(Hoge).to receive(:hoge) { n += 1 }
Hoge.new.hoge
Hoge.new.hoge
Hoge.new.hoge
expect(n).to eq(3)
end
end
module Foo
def foo; end
end
class Bar
include Foo
end
describe 'Bar' do
it 'raise error with exactly matcher' do
expect_any_instance_of(Bar).to receive(:foo).exactly(1).times
Bar.new.foo
expect { Bar.new.foo }.to raise_error(/The message 'foo' was received by #<Bar:.+ >/)
end
it 'succeeds with giving proc' do
n = 0
allow_any_instance_of(Foo).to receive(:foo) { n += 1 }
Bar.new.foo
Bar.new.foo
Bar.new.foo
expect(n).to eq(3)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment