ruby on rails - How to stub a method on a model copy in rspec? -


say have next code:

class foo < activerecord::base    def self.bar     all.each(&:bar)   end    def bar     # want stub in test   end end 

now want create test (rspec):

foo = foo.create expect(foo).to receive(:bar) foo.bar 

this test not pass because foo.bar calls other instance of same model foo.

i wrote complex code in such situations before, like:

expect_any_instance_of(foo).to receive(:bar) 

but not good, because there no confidence foo receives message (there several instances). , expect_any_instance_of not recommended rspec maintainers.

how test such code, best practice?

if want fine grained control on each instance, can this:

foo_1 = foo.create expect(foo_1).to receive(:bar).and_return(1) foo_2 = foo.create expect(foo_2).to receive(:bar).and_return(2)  # makes our specific instances of foo_1 , foo_2 returned. allow(foo).to receive(:all).and_return([foo_1, foo_2])  expect(foo.bar).to eq [1, 2] 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -