Is it good to use database queries in Rspec?
mocking, rspec, ruby-on-rails, stubbing
Solution
When you are testing a model, it's good to let your tests integrate against the database. That is, don't try to mock out the ActiveRecord stuff, and just use a model object. FactoryGirl and Fabrication are both just convenient shortcuts to building real model objects, and they are best practises when it comes to testing ActiveRecord models.
Since this is legacy code, I would suggest not mocking or stubbing too much in the old code, because isolation only works if each component is tested in isolation.
However, when writing code with TDD, mocking and stubbing has many benefits:
- Gives you fine grained tests (if a method breaks, your tests tell you which one)
- Your tests run much faster, and thus your TDD cycle is shorter
- Lets you make assertions about how your code interacts with other objects
- If you have to stub and mock other models excessively to isolate one model, it is usually a good sign that your code is too highly coupled and deserves a refactor
Problem
I have started writing tests using Rspec for a really old project. The models which i am testing are all ActiveRecords(backend is Oracle). I have read some blogs that say we should use mocking and stubbing/fixtures/factory girl over firing an actual sql. I am confused. I will have to stub a lot of methods and create lot of objects. Is this a good practice ?