Upload
darcy-holland
View
212
Download
0
Embed Size (px)
Citation preview
Testing
Carol WolfComputer Science
Testing built into Rails Rails comes with three databases.
development test production
The test database does not contain your important data. It can be filled and emptied without causing problems.
Run with rake test. Described in config/database.yml
yml is short for yaml yaml stands for yaml ain’t markup language yaml is simpler than xml It shares the descriptive purpose of xml An example is on the next page.
development:
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000
test:
adapter: sqlite3
database: db/test.sqlite3
pool: 5
timeout: 5000
production:
adapter: sqlite3
database: db/production.sqlite3
pool: 5
timeout: 5000
config/database.yml for MySqldevelopment:
adapter: mysql2encoding: utf8database: name_developmentpool: 5username: rootpassword: mypasswordsocket: /tmp/mysql.sock
test folder Each application has a test folder. Sub folders
fixtures – used for sample data functional – tests the controller integration – tests interacting controllers performance – benching and profiling unit – tests for models
The scaffold command populates all the sub folders except for integration.
An example is on the next slide.
fixtures/books.yml
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
one: isbn: MyString author: MyString title: MyString
two: isbn: MyString author: MyString title: MyString
Fixtures When testing with rake test
Empties test database Loads fixtures data Puts fixtures data in a variable for saving
Fixtures are in the form of hashes Can write: books(:Dickens).title
Fixtures can include ERB Specific tests can be run using rake
test:fixtures, rake test:functionals, etc.
Unit Tests Unit tests are used for models, i.e. database tables. They contain assertions
assert book.invalid? assert book.errors[:isbn].any?
The names in quotes will be replaced by names with underscores.
require 'test_helper'
class BookTest < ActiveSupport::TestCase# Replace this with your real tests.test "the truth" do
assert trueend
end
Replace book_test.rb with following:require 'test_helper'
class BookTest < ActiveSupport::TestCase# Replace this with your real tests.test “book attributes may not be empty" do
book = Book.newassert book.invalid?assert book.errors[:isbn].any?assert book.errors[:author].any?assert book.errors[:title].any?
endend
Functional tests Used to test controllers book_controller_test.rb contains tests for each
method in the book controller Below the test for the create method. Its parameters are sent with a post method
test "should create book" doassert_difference(‘Book.count') do
post :create, :book => @book.attributesendassert_redirected_to book_path(assigns(:book))
end
Our book_controller_test.rbtest "should create book" do
assert_difference('Book.count') dopost :create, :book => { :isbn => '2345',
:title => 'Emma', :author => 'Austen‘ }
endassert_redirected_to book_path(assigns(:book))
end