Search code examples
ruby-on-railsrubyruby-on-rails-3rspecrspec-rails

Rspec allow_any_instance_of to return instance id


Is it possible to do something like this???

allow_any_instance_of(Object).to receive(:foo).and_return("hello #{instance.id}")

Can i return a message depending on the instance?


Solution

  • Yes, using the "block" form of the matcher, which gives you access to the instance as the formal parameter to the block. You also need to make sure that Object (or whatever class you are passing to allow...) implements :foo (or whatever method you are specifying) as an instance method, or the allow... will raise an error. Similarly, of course, you need to make sure that id is implemented as well.

    Here is some sample code using Object itself:

    class Object
      def id
        'bar'
      end
      def foo
      end
    end
    describe '' do
      it '' do
        allow_any_instance_of(Object).to receive(:foo) { |o| "hello #{o.id}" }
        puts Object.new.foo
      end
    end