I have a statement like Model.some_scope.pluck(:a_field) in a method I'd like to test.
What's the recommended way for me to stub the return value of this chained method call statement with rspec-mocks 3.4.0? I saw that stub_chain and receive_message_chain are both listed as old syntax on the RSpec website.
Best Regards.
The cleanest way to test that code is to extract a method, e.g.
class Model < ActiveRecord::Base
def self.some_scope_fields
some_scope.pluck(:a_field)
end
end
That method can be stubbed without a chain.
However, there are times when it's neither convenient nor idiomatic to do that. For example, it's idiomatic, and not a Law of Demeter violation, to call create on an ActiveRecord model's association methods. In those cases,
if you don't care about method arguments, use receive_message_chain. stub_chain is deprecated; receive_message_chain is not. What the receive_message_chain documentation says is that "support for stub_chain parity may be removed in future versions". The issue linked to from that documentation makes it clear that "stub chain parity" means the use of with with receive_message_chain. So do use receive_message_chain; just don't use with with it.
if you do care about method arguments, use doubles. For example, for the code you gave,
scope = double
allow(scope).to receive(:pluck).with(:a_field) { # return whatever }
allow(Model).to receive(:some_scope).with(no_args) { scope }
Related
I have a strange issue with receive_message_chain rspec 3.6
allow_any_instance_of(Order).to receive_message_chain('line_items.find')
{LineItem.first}
When i do a order.line_items instead of returning a collection it returns me a <Double (anonymous)> object which is not what i wanted.
Any suggestions??
When you tell RSpec to set receive_message_chain('line_items.find') on a specific object, it needs set the correct stubs in place for the chain to work.
First RSpec stubs the method line_items on the object. Next it needs to stub the method find, but this method needs to be stubbed on the return value of the method line_items. Since we stubbed that method, RSpec needs to come up with a some return value, that can be the target of the stubbing.
So RSpec sets the return value of the method line_items to be an anonymous double that has the the method find stubbed. Because of this once you set the receive_message_chain with 'line_items.find', the object will always return an anonymous double when line_items is called. And since you use allow_any_instance_of, this means that the method line_items is now stubbed on all the instances of Order.
I would recommend thinking about trying to remove the uses of allow_any_instance_of and receive_message_chain from your specs if it is possible, since they are really shortcuts to be used in specs if you really cannot change the design of your code. https://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/message-chains
However if that is not possible, you can remove the receive_message_chain and set the chain yourself.
line_items_stub = double
# or line_items_stub = Order.new.line_items
# or line_items_stub = [LineItem.new, LineItem.new]
# or line_items_stub = the object that you want
allow_any_instance_of(Order).
to receive(:line_items).
and_return(line_items_stub)
allow(line_items_stub).to receive(:find)
If you were able to remove the allow_any_instance_of you could use and_call_original to call the for real implementation of line_items on that concrete instance you are stubbing the message_chain on.
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
I'm working through Michael Hartel's rails tutorial, on 6.3 and need alternative code for the user_spec model. The code that he has is:
let(:found_user) { User.find_by(email: #user.email) }
It looks like I can use where, but unsure of the correct syntax. I tried several variations of the following:
let(:found_user) { User.where(:email => "#user.email")}
I'm sure this is a pretty easy answer, but cant quite get it.
let(:found_user){User.where(email: #user.email).first}
or
let(:found_user){User.find_by_email(#user.email)}
That first one that uses where returns a collection of users that match the where clauses, which is why you would need that .first (It doesn't execute the sql until you grab the records with something like .all, .first, or .each).
I would say it's not the best practice to execute database commands in a unit test though. What are you testing specifically? Is there a reason you need the user to be saved in the database and can't just do something like:
let(:user){User.new(email: 'some email')}
ActiveRecord::Base#find_by is effectively where(options).first, but that's a whole extra call that you needn't make.
Rails also provides mildly deprecated "magic" find_by_<attribute>[and_<attribute>] methods which used method_missing to parse out what was meant based on the name of the method. While the framework does provide these, I caution against using them as they are necessarily slower than "native" methods, and are more resistant to refactoring.
I would recommend sticking with find_by for the general case, and would try to avoid hitting the database in specs and tests.
The factory_girl gem provides a method to create a stubbed version of the class which quacks like a record returned from the database by answering true for persisted? and providing an id.
Alternatively, you can just build a new record without saving it: User.new(attribute: value, ...) and run your tests on that:
it "does some things" do
user = User.new(attributes)
# make user do some things
expect(things).to have_happened
end
I ran into an issue with my RSpec specifications and ActiveRecord scopes today.
I have a controller that executes code similar to this
#customers = Customer.active.with_counts.order('name asc')
‘active’ and ‘with_counts’ are scopes on the Customer model.
I used to have a specification that used stub_chain like this:
Customer.stub_chain(:with_counts, :order).with('name asc') { [mock_customer] }
I did not expect this to succeed since the controller included the ‘active’ scope but to my surprise it succeeded without any problems.
I guess that the ‘active’ scope is called on the real Customer class and returns something that the stub_chain sort of connects to and it therefore appears to work.
How can I write my specification to avoid this kind of issue when I chain ActiveRecord scopes?
Note that the actual call in the controller will not always used both scopes - it is dependent on filtering so just wrapping everything in a new method is not a way that I am keen to go.
I am using FactoryGirl and Rspec for testing.
The model sets a foreign key after init if it is nil. Therefore it uses data of another association. But how can I test it?
Normally I would use a factory for creation of this object and use a stub_chain for "self.user.main_address.country_id". But with the creation of this object, after initialize will be invoked. I have no chance to stub it.
after_initialize do
if self.country_id.nil?
self.country_id = self.user.main_address.country_id || Country.first.id
end
end
Any idea?
Ideally it's better that you test behavior instead of implementation. Test that the foreign key gets set instead of testing that the method gets called.
Although, if you want to test the after_initialize callback here is a way that works.
obj = Model.allocate
obj.should_receive(:method_here)
obj.send(:initialize)
Allocate puts the object in memory but doesn't call initialize. After you set the expectation, then you can call initialize and catch the method call.
Orlando's method works, and here's another which I'd like to add. (Using new rspec 'expect' syntax)
expect_any_instance_of(Model).to receive(:method_here)
Model.new
Another approach is to refactor your code to allow simple unit tests. As is, your code is approaching the upper end of how much code I'd put in a callback:
after_initialize do
if self.country_id.nil?
self.country_id = self.user.main_address.country_id || Country.first.id
end
end
If it grew much more, I'd extract it to a method and reduce your callback to a method call:
after_initialize :init_country_id
def init_country_id
if self.country_id.nil?
self.country_id = self.user.main_address.country_id || Country.first.id
end
end
The bonus here is that testing init_country_id becomes just another method unit test at this point...nothing fancy about that.
Now that you've got a unit test on the behavior, you can also test that it gets called, if you're in doubt. (Something as simple as after_initialize :init_country_id does not need invocation testing, IMO)
You can use gem shoulda-callback-matchers to test that your callbacks are actually getting triggered as intended:
it { is_expected.to callback(:init_country_id).before(:initialize) }