Steve
Steve

Reputation: 4566

Proper usage of CRUD operations in unit tests

I would like to have a varying number of records saved to the database for different tests. The purpose of one test would be to see a method's behavior with only one record in the database while another might be to see how the method behaves with ten records. I understand Fixtures are the preferred way to load data into the testing database, but as far as I know, Fixtures are static and can't be molded for a specific test. I am therefore, using CRUD operations in some of my tests. Most of these tests begin by deleting all the records from the table being tested then adding records that suit the specific test.

The tests that rely on CRUD operations and do not use Fixture data I have placed at the end of my tests so they don't interfere with the tests that use Fixtures. I am new to testing in Rails and would like to know if bypassing Fixtures and using CRUD operations in unit tests is a good/bad practice?

Upvotes: 1

Views: 291

Answers (1)

TK-421
TK-421

Reputation: 10763

You'll see all kinds of answers, from using fixtures to factories to POROs ("Plain Old Ruby Objects"), but I think in general you want to minimize or eliminate database interaction as much as possible when working at the unit testing level, while leaving that more for integration or acceptance tests.

While unit testing, it might be helpful to think about inputs and outputs, and how/what messages are sent to and from each "unit" under test.

There are plenty of books, articles, and posts out there on this topic, but in the end I'd recommend a balance between practicality and the ideal worldview some of these present.

You might find this interesting:

https://www.youtube.com/watch?v=qPfQM4w4I04

Upvotes: 1

Related Questions