Model Testing
Learn about the test database, model testing in Rails, and write tests for your Link model.
We'll cover the following
Test database
Since your application relies heavily on interactions with a database, you need to have one in your testing environment. Rails provides a dedicated test database allowing you to run your tests in isolation, without having to worry about tampering with your development database.
Loading the database schema
To load the database schema for your test environment you will run:
rake db:schema:load RAILS_ENV=test
This loads the schema from your db/schema.rb
file for your test database.
Note: This command will raise an error if there are any pending migrations.
Populating the database
To populate your database, you need to use test/fixtures/links.yml
file (this file is auto-generated for your Link
model when using scaffolding):
linkOne:
url: mysite.com
linkTwo:
title: myTitle
url: anothersite.com
linkOne
and linkTwo
from your fixture file are ActiveRecord
instances. This means you can use methods available to the Link
class on them.
id1 = links(:linkOne).id
# the id of linkOne will be stored in id1
You will load the fixtures using the following command:
rake db:fixtures:load RAILS_ENV=test
Note: Every Rails app has three environments: development, production, and test. You need to use
RAILS_ENV
to specify that you are using the test environment.
Now that you have loaded your schema and added a few entries, you can begin writing your tests.
Get hands-on with 1400+ tech skills courses.