[rspec-users] Smart mocks for ActiveRecord to speed up tests

Rodrigo Rosenfeld Rosas lbocseg at yahoo.com.br
Mon Apr 16 12:27:14 UTC 2012

Thank you David and Matt for your comments.

Indeed I had considered using FakeWeb but I thought that maybe there 
could be an easier way just to mock 'open' directly since I guess it 
would be faster to run.

With regards to the work around to overcome the issue with mocking AR so 
that I could speed up my tests I think that creating helpers in the 
model that will restrict the use of the AR API sounds like a good 
balance, but that wouldn't make my specific tests faster.

Here is why: my Model class shouldn't be created or updated by any other 
code in my application. So I'd just have to add a new method to the 
Model class that would be specific to this action and I'd need to write 
a "unit" test for this new method. I quoted "unit" because it is 
actually an integration test as it will touch the database or otherwise 
I wouldn't be able to upgrade Rails to a new version if I'm mocking some 
methods from AR and they change in a future version.

So I'd need to touch the database anyway and my 9 specs would still take 
almost a full second to run while this specific controller spec takes 
about 0.7s (up to 2s depending on my system load).

Well, actually, I guess RSpec has changed the way it measure spec runs 
since I last used it. I'm saying that because it will report me from 0.7 
to 2s when I run "rspec path/to/my_controller_spec.rb", but if I run 
"rspec --profile" it will run the full suite about the same time and 
this specific controller action will take 0.38s.

Anyway, I don't see how I would create hundreds of specs and expect them 
to run in a few seconds and still have a reliable test suite. I mean, I 
want to feel safe if I'm upgrading to a newer Rails version even if it 
changed its AR API.

The only real improvements I can see for my tests running fasts without 
changing anything in the specs is to use something like Hydra so that I 
could use the full power of my 6-core processor.

Does RSpec has a built-in threaded option? I guess not because I don't 
think it would be much effective on CRuby because it would probably lock 
on database access (or maybe not, I don't know how the pg driver is 
implemented). For my particular application I suspect it is not 
cpu-heavy, but io-expensive instead. So maybe a multi-thread spec runner 
could improve its performance when running multiple specs.


More information about the rspec-users mailing list