RubyDubee
RubyDubee

Reputation: 2446

How do i stub a method/attribute of all instances of a class based on another attribute value?

Either this doesn't exist or i am looking at this the wrong way.

In rspec, I want to stub a method/attribute of all the instances of a class but only if that instance follows a certain condition, for example:

the following code will stub all posts with given comments:

Post.any_instance.stub(:comments).and_return([comment1, comment2])

but I only want to stub comments if the post is published, otherwise i want a blank comments array.

Is there any way I can do something like this:

Post.any_instance.stub(:comments) do |post|
  post.published ? [comment1,comment2] : []
end

I have seen solutions where you send an argument to the stubbed method and based on argument value you can return different values, but that's not the case here.

Upvotes: 2

Views: 1289

Answers (1)

Peter Alfvin
Peter Alfvin

Reputation: 29379

The code you've included should work fine. Stubbing with a block is documented in https://relishapp.com/rspec/rspec-mocks/v/3-3/docs/old-syntax/any-instance#block-implementation-is-passed-the-receiver-as-first-arg, although it's deprecated now in favor of the new methods described at https://relishapp.com/rspec/rspec-mocks/v/3-3/docs/working-with-legacy-code/any-instance

Upvotes: 1

Related Questions