Mocha on Ruby: Check a stubbed function called once - ruby-on-rails

It should be straight forward, but it doesn't work for me.
I'm stubbing a function call, and I want to make sure it is called once, so I did:
MyClass.stubs(:record).returns(true).expect(:record).once
MyClass.run
but I keep getting:
expected exactly once, not yet invoked: allowed any number of times, invoked once: MyClass.record(any_parameters).record(any_parameters)
What am I doing wrong?

Are you trying to set expectations for 2 separate invocations on record?
stubs is just a syntactic sugar for expects, specifying that you expect an invocation zero or more times.
You could probably rewrite your example as such:
MyClass.expects(:record).returns(true)
Keep in mind that expects is by default implying the once part although you could add it if you think that it adds to your code's clarity.

Related

Allow mocks (double("object")) to respond to :call or :send like the supplied method?

In a little refactoring mode, and I have a bunch of tests that have doubles that are stubbing out method calls, e.g.:
connection = double("api_connection", create_thing: double("thing"))
In this example, calling connection.create_thing returns me the thing double, as expected.
However, I've now changed the code so that the actual code is running like:
connection.send(:create_thing)
Which is causing a slew of errors:
Double "api_connection" received unexpected message :call with (:create_thing)
Since this is a refactor, I am reticent to just fix the test doubles to respond to call. Is there a way to set these doubles to accept :call like they'd accept whatever method is being passed to :call?
Well, this turned out to be a PEBCAK error.
:call is not a ruby object method -- what I was intending to use was :send. Replacing my code with :sendss where I had those :calls caused everything to work.
Good thing I didnt try to 'fix' the tests -- they were failing correctly.

Rspec mocks, can 'expect' also stub a method as a side effect?

I'm trying to make sense of the tests in an inherited app, and I need some help.
There are lots of spec groups like this one (view spec):
let(:job_post) { FactoryGirl.create(:job_post) }
# ...
before do
expect(view).to receive(:job_post).at_least(:once).and_return(job_post)
end
it "should render without error" do
render
end
... with job_post being an helper method defined on the controller. (yes, they could have used #instance variables, and I'm in the process of refactoring it).
Now, in my opinion using an expect inside a before block is wrong. Let's forget about that for a second.
Normally the test above is green.
However, if I remove the expect line, the test fails. It appears that in this case expect is stubbing the method on the view. In fact, replacing expect with allow seems to have exactly the same effect.
I think that what's going on is that normally – when run with a server – the view will call job_posts and the message will land on the helper method on the controller, which is the expected behaviour.
Here, however, expect is setting an expectation and, at the same time, stubbing a method on the view with a fixed return value. Since the view template will call that method, the test passes.
About that unexpected "stub" side effect of expect, I've found this in the rspec-mocks readme:
(...) We can also set a message expectation so that the example fails if find is not called:
person = double("person")
expect(Person).to receive(:find) { person }
RSpec replaces the method we're stubbing or mocking with its own test-double-like method. At the end of the example, RSpec verifies any message expectations, and then restores the original methods.
Does anyone have any experience with this specific use of the method?
Well, that's what expect().to receive() does! This is the (not so) new expectation syntax of rspec, which replaces the should_receive API
expect(view).to receive(:job_post).at_least(:once).and_return(job_post)
is equivalent to
view.should_receive(:job_post).at_least(:once).and_return(job_post)
and this API sets the expectation and the return value. This is the default behavior. To actually call the original method as well, you need to explicitly say so:
view.should_receive(:job_post).at_least(:once).and_call_original
On to some other issues:
(yes, they could have used #instance variables, and I'm in the process of refactoring it).
let API is very ubiquitous in rspec testing, and may be better than #instance variables in many cases (for example - it is lazy, so it runs only if needed, and it is memoized, so it runs at most once).
In fact, replacing expect with allow seems to have exactly the same effect.
The allow syntax replaces the stub method in the old rspec syntax, so yes, it has the same effect, but the difference is, that it won't fail the test if the stubbed method is not called.
As the OP requested - some explanations about should_receive - unit tests are expected to run in isolation. This means that everything which is not directly part of your test, should not be tested. This means that HTTP calls, IO reads, external services, other modules, etc. are not part of the test, and for the purpose of the test, you should assume that they work correctly.
What you should include in your tests is that those HTTP calls, IO reads, and external services are called correctly. To do that, you set message expectations - you expect the tested method to call a certain method (whose actual functionality is out of the scope of the test). So you expect the service to receive a method call, with the correct arguments, one or more times (you can explicitly expect how many times it should be called), and, in exchange for it actually being called, you stub it, and according to the test, set its return value.
Sources:
Message expectation
RSpec's New Expectation Syntax
Rspec is a meta-gem, which depends on the rspec-core, rspec-expectations and rspec-mocks gems.
Rspec-mocks is a test-double framework for rspec with support for method stubs, fakes, and message expectations on generated test-doubles and real objects alike.
allow().to receive
is the use of 'Method Stubs', however
expect().to receive
is the use of 'Message Expectations'
You can refer to the Doc for more details
If you don't want to stub as a side affect, you can always call the original.
https://relishapp.com/rspec/rspec-mocks/v/2-14/docs/message-expectations/calling-the-original-method
For example I once wanted to spy on a method, but also call the function else it has other side affects. That really helped.
https://relishapp.com/rspec/rspec-mocks/v/2-14/docs/message-expectations/calling-the-original-method

Mocha Rails Weirdness

I'm seeing a very weird output from my Rails tests, using Mocha and Rails 3.1.0.
not all expectations were satisfied
unsatisfied expectations:
- expected exactly once, not yet invoked: #<GitAccess:0xbb5c344>.branches(any_parameters)
satisfied expectations:
- allowed any number of times, invoked once: #<GitAccess:0xbb5c344>.branches(any_parameters)
It says that my "branches" method was never called, but called once - on the same object? How is this possible? My controller looks like this:
def create
git_access.branches()
end
I'm totally not understanding how this is possible.
Okay, here's the answer. I somehow thought that .expects would only check whether the function is called or not. So in my test I had .expects and .stubs on the same function call, which made mocha ignore my .stubs.
By reading a bunch of tutorials online, .stubs should be used when you want to fake the response of a method, and .expects when you want to fake the response of a method AND test whether the method is called.

Set an expectation without mocking anything

Using MiniTest::Spec and Mocha:
describe "#devices" do
it "scopes the devices by the provided :ip_list" do
ips = 'fast tests ftw!'
ds = DeviceSearch.new ip_list: ips
Device.expects(:scope_by_ip_list).once.with(ips)
ds.devices
end
end
When I make the code work correctly, this test will fail, because calling Device.expects(:scope_by_ip_list) also stubs Device.scope_by_ip_list, and since I don't specify a .returns(Devices.scoped) or some such, it stubs out the method with nil. So, in my code which properly scopes a list of devices and then does further operations, the further operations blow up.
I don't want to have to specify a .returns parameter, though, because I totally don't care what it returns. I don't want to stub the method at all! I just want to set up an expectation on it, and leave it functioning just the way it is.
Is there a way to do that?
(To me, it seems very awkward to say something like Device.expects(:foo).returns('bar')—when I say that Model expects method, I'm not saying to stub that method! We can say Device.stubs(:foo), if we want to stub it.)
The behavior is intended and can't be changed. Look at the following post to see how it can be circumwented:
rspec 2: detect call to method but still have it perform its function

How do I find where a ruby method is declared?

I have a ruby method (deactivate!) that is on an activeRecord class. However, I can't seem to find where that method is declared.
There have been numerous developers on this project, so it could be anywhere. There is a deactivate! on an unrelated class, but it doesn't seem to get called.
Any ideas how to find all the superclasses for an instace, or where to find the code for deactivate!?
First question would be: is it an actual method? Does obj.method(:deactivate!) raise an error?
If it doesn't, then you can use Method#source_location(in Ruby 1.9 only, and backports can't support it):
obj.method(:deactivate!).source_location
If it does raise a NoMethodError, it is handled via method_missing. This makes it hard to track. If it accepts arguments, I'd try sending the wrong type and using the backtrace of the raised exception.
Are you using state_machine? If you have an event transition called :deactivate, the model will have the method #deactivate! created automatically.
When I need to find where a method is declared on some class, say 'Model', I do
Model.ancestors.find {|c| c.instance_methods(false).include? :deactivate! }
This searches the ancestor tree in the same order that ruby does for the first that has the method in instance_methods(false), which only includes non-inherited methods.
Note: before ruby 1.9, the methods were listed as strings not symbols, so it would be
Model.ancestors.find {|c| c.instance_methods(false).include?('deactivate!') }
As a first stab, try the Jump to Declaration feature of your IDE. Depending on how good your IDE's static type inference is, it should take you right there.
If that doesn't work, set a breakpoint on that call, fire up the debugger and step into the method.

Resources