Ruby on Rails: Testing, Configuration, and Forms in Rails April 8th, 2015

  • There’s a default testing framework in Ruby 1.9+
    • Borrows from Test::Unit and RSpec
    • Choose one or the other to write all your tests in; don’t use both … be consistent
  • Rails provides testing support out of the box
    • Test runner (via Rake)
    • Testing models against the database using fixtures
    • Functional testing controllers (e.g. that the create action in a controller saves a new model)
    • Integration tests (e.g. testing application flow through multiple controllers)
    • Support for testing mailers and helpers
  • Tests are run against a test database
  • Isolates testing from other environments (e.g. development and production)
  • After you run a migration, run: rake db:test:prepare
  • Rails automatically:
    • Cleans the test database before each test
    • Starts a database transaction before each test
    • Rolls back the transaction after each test to ensure each test has a known state
      • Is much faster (since changes don’t hit disk)
      • Keeps tests isolated (consistent state before & after tests)
      • Makes tests easier to implement (no messy data setup, teardown, or consistency checks needed)
  • Not really “unit” testing since testing against a live database is more integration testing than unit testing
  • rake –all -T to list all tasks even if it doesn’t have a description such as test:models
  • Fixtures populate the test database
  • Rails is configured through a few .rb and .yml files
  • Database connection information is stored in database.yml
  • 7 standard RESTful routes in Rails
    • index, new, show, create, edit, update, destroy
    • Rails calls it Resource Routing
    • Representational State Transfer
      • An architectural style described by Roy Fielding in his 2000 Ph.D. thesis
      • Key properties:
        • Resources operated on by actions (e.g. HTTP PUT)
        • Actions are constrained to limited but consistent set
        • Stateless (all necessary state is supplied in actions)
        • Scalability (due to stateless nature)
  • Partials are a way to extract shared view code in templates
    • Partial names begin with an underscore, e.g. /app/views/books/_form.html.erb
    • When you render partials, you exclude the underscore, e.g. ‘form’
    • You can pass arguments to partials
      • Typical use is to pass a collection of models
      • Partial is rendered once for each object in collection
      • You can reference the object from within the partial

Resources