Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.any_instance should_receive vs expect() to receive

The following piece of code works as expected:

Object.any_instance.should_receive(:subscribe) 

But when using the new rspec expectation it does not work:

expect(Object.any_instance).to receive(:subscribe) 

The error is:

expected: 1 time with any arguments received: 0 times with any arguments 

How can I make this work with expect() to receive?

like image 609
Calin Avatar asked Jul 10 '13 09:07

Calin


People also ask

What is the difference between expected and received objects?

That is, the expected object is a subset of the received object. Therefore, it matches a received object which contains properties that are present in the expected object. Instead of literal property values in the expected object, you can use matchers, expect.anything (), and so on.

Will expect_any_instance_of fail if no instance receives a message?

The spec will fail if no instance receives a message. the output should contain "1) expect_any_instance_of fails unless an instance receives that message" Last published about 6 years ago by myronmarston.

What is the difference between “allow” and “expect” in JavaScript?

That is allow allows an object to return X instead of whatever it would return unstubbed, and expect is an allow plus an expectation of some state or event. When you write ... you're telling the spec environment to modify Foo to return foobar_result when it receives :bar with baz.

How do I mock any instance of a class in RSpec?

Any Instance. rspec-mocks provides two methods, allow_any_instance_of and expect_any_instance_of, that will allow you to stub or mock any instance of a class. They are used in place of allow or expect:


1 Answers

There's now a not very well documented method called expect_any_instance_of that handles the any_instance special case. You should use:

expect_any_instance_of(Object).to receive(:subscribe) 

Google expect_any_instance_of for more info.

like image 143
Peter Alfvin Avatar answered Oct 16 '22 02:10

Peter Alfvin