Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good to use database queries in Rspec?

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 ?

like image 739
Rima Avatar asked Sep 02 '25 09:09

Rima


2 Answers

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
like image 114
cjhveal Avatar answered Sep 04 '25 21:09

cjhveal


Normally you would use stubs, then you can run tests without loading AR, and they will run a lot faster.

Personally I believe that testing fake data is no test... Maybe in a development environment doing TDD... Maybe..., but for a test environment it should be as close to the real thing as possible.

This is of course my opinion and may not be the current school of thought.

like image 34
cpuguy83 Avatar answered Sep 04 '25 21:09

cpuguy83