O'Reilly logo

Rails 4 Test Prescriptions by Noel Rappin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

What’s the Problem?

What’s the big deal if I want to use normal, ordinary ActiveRecord#create in my tests? I use it in my code. What could go wrong?

Since you asked…

We’ll start with a simple test involving two users:

 
it ​"can tell which user is older"​ ​do
 
eldest = User.create(date_of_birth: ​'1971-01-22'​)
 
youngest = User.create(date_of_birth: ​'1973-08-31'​)
 
expect(User.find_eldest).to eq(eldest)
 
expect(User.find_youngest).to eq(youngest)
 
end

That test is deliberately simple, so as not to distract from the data-creation issue. The only weird thing here is that we are testing a hypothetical finder method, find_eldest, that actually goes into the database, so it’s necessary for the test that the objects actually make it all the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required