Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fake an active record model without db

I feel like I've got to me missing something. I'm writing a ruby gem that allows interaction with active record as an add on to its primary function.

In writing test cases for it, I need to be able to specify dummy active record models to test this functionality. It would be superb if I could get an instance of an active record model that didn't need any connection to a db, that could have relations, all that stuff, but didn't require me to setup tables in a database. I'm fairly new to testing, and outside of rails testing i'm pretty dang new, but it seems like I should be able to do something like that fairly easily, but I'm not finding anything.

Can anyone tell me what I'm missing? I've looked at factories, fabricators, fixtures, all those seem to want to hit the db. How do people test gems where you need AR object only for testing?

like image 754
rm-rf Avatar asked Sep 28 '11 16:09

rm-rf


People also ask

Is ActiveRecord a database?

1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

Is ActiveRecord ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is an ActiveRecord relation?

The Relation Class. Having queries return an ActiveRecord::Relation object allows us to chain queries together and this Relation class is at the heart of the new query syntax. Let's take a look at this class by searching through the ActiveRecord source code for a file called relation.


1 Answers

It sounds like you need NullDB:

NullDB is the Null Object pattern as applied to ActiveRecord database adapters. It is a database backend that translates database interactions into no-ops. Using NullDB enables you to test your model business logic - including after_save hooks - without ever touching a real database.

like image 163
Andy Waite Avatar answered Sep 24 '22 01:09

Andy Waite