Archive for the ‘Ruby on Rails’ Category

Testing in Rails: Part 7 - ActiveRecord Relationships

Tuesday, January 8th, 2008

This is part of an ongoing series of posts about how to get started writing tests for Ruby on Rails. The series begins with the introduction and overview of the ideas behind testing.

Unit Testing ActiveRecord

Wine Grapes

In the unit tests we wrote previously, we tested everything in the class. The rule of thumb was that everything needs to be tested. That has not changed now that we are working with ActiveRecord—each method still needs a test.

But what testing should be done on the basic database CRUD (Create, Read, Update, Delete)? After all, that is what is most different about classes that inherit from ActiveRecord, right? It may surprise you to learn that we do not need to test basic CRUD.

Why not? ActiveRecord handles all of our database activity for us. It knows how to connect to the database, how to create, find, read, update, delete, use conditions and sort. That is the reason why we are using a framework like Rails to begin with: because we can inherit all that ActiveRecord goodness without having to rewrite it ourselves. We can trust that ActiveRecord will do its job correctly.

photo by Tomás Castelazo

That is not blind trust—ActiveRecord has its own unit tests that the core Rails team uses to insure that it works properly. Therefore we can assume that everything our class inherits from ActiveRecord is solid and tested. It was unit tested before we installed it. We just need to focus on our code in the subclass.

The corollary to “Test Everything” is: “If it is code you added, it is code you need to test.”

(more…)

Testing in Rails: Part 6 - Fixtures

Friday, December 21st, 2007

This is part of an ongoing series of posts about how to get started writing tests for Ruby on Rails. The series begins with the introduction and overview of the ideas behind testing.

Fixtures

In the most general terms, a test fixture is an environment for running tests which is in a fixed state (i.e. it is ‘fixed’). While the term is primarily associated with software development, it applies to any testing environment.

Think back to our car battery example for a moment. If we unit test the battery inside the car, there is a chance that our testing environment will throw off the results. Ideally, we would remove the battery from the car and put it in a test environment that we know is stable, thereby removing as many variables and potential sources of error as possible. Then our unit test results should be predictable, accurate and repeatable. The environment we put the battery in—the meters, the wires attached to it, the amount of voltage we put in or out, etc.—is the test fixture. It will stay the same during each test we run on the battery.

Racetrack

You have encountered fixtures in other contexts before without knowing it. A race track is an example of fixture. The cars and drivers racing around it are different, but the pavement and curves are the same for everyone. When a race (which is essentially a benchmark test) pits the cars against each other, the fixtures are important in ensuring that the winner is meaningful. Everyone faces the same conditions, yet one car will be faster than the rest. If every car raced on a different course the race results would be meaningless. Sports and competitive events are filled with examples of fixtures—generally known as “having a level playing field.”

The idea is to fix the environment so that the environment will not skew the results.

(more…)

Testing in Rails: Part 5 - Unit Testing ActiveRecord Models

Friday, December 7th, 2007

This is part of an ongoing series of posts about how to get started writing tests for Ruby on Rails. The series begins with the introduction and overview of the ideas behind testing.

Setting Up for Unit Testing ActiveRecord Models

Wine

In the previous section, we saw that running unit tests inside the Rails framework is not that different from running tests outside it. We have learned how to test the Car class in both Ruby and Rails. But Car does not inherit from ActiveRecord::Base (or, if yours did, our tests did not probe any ActiveRecord traits). Let’s see how our unit tests would be different if our class was using ActiveRecord to store instances in a database.

For this example, we will keep using the same sample application, but we will move away from cars and create two new classes: Winery and Wine. Each winery will produce several different wines. We start by using script/generate to create our two models.

script/generate model Winery
script/generate model Wine

The generator will create the model, a migration, a skeleton for your unit test and even a fixture file we will use later, all in one easy step. You do not need to worry about creating controllers, scaffolding or views. They are irrelevant for unit testing.

(more…)

Testing in Rails: Part 4 - Unit Testing in Rails

Thursday, November 29th, 2007

This is part of an ongoing series of posts about how to get started writing tests for Ruby on Rails. The series begins with the introduction and overview of the ideas behind testing.

Unit Tests + Rails

After so much discussion of unit testing in Ruby you are probably anxious to start applying your new-found skills to a Rails application. The good news is that everything you have learned so far is directly applicable to testing in Rails.

When you first create a new Rails application (e.g. rails sample_app), a folder called ‘test’ is created in your application’s root directory. This is the folder where all of your test code will reside.

Test Folder

As you would expect, we will be putting all of our application’s unit tests inside the subfolder called ‘unit’. At first that folder will be empty. When a new model is generated, the generator script will also create a skeleton for unit testing that model.

(more…)

Testing in Rails: Part 3 - Unit Testing Ruby Classes (cont.)

Tuesday, November 20th, 2007

This is part of an ongoing series of posts about how to get started writing tests for Ruby on Rails. The series begins with the introduction and overview of the ideas behind testing.

Testing the colors Method

Now that we have examined the thought process behind writing tests, I will move more quickly through test_colors and test_full_name. test_colors is simple: invoking colors on the class Car will return an array of colors. How much and what kind of testing this requires is up to you and really depends on your application’s usage. Here are some examples:

def test_colors
    assert(Car.colors.kind_of?(Array))
    assert_equal(4, Car.colors.length)
    assert_equal(['blue', 'black', 'red', 'green'], Car.colors)
    assert(Car.colors.include?(@volvo.color))
    assert(Car.colors.include?(@honda.color))
    assert(!Car.colors.include?(@dodge.color))
    assert(!Car.colors.include?(Car.new.color))
  end

(more…)

Testing in Rails: Part 2 - Unit Testing Ruby Classes

Saturday, November 17th, 2007

Cars

This is part of an ongoing series of posts about how to get started writing tests for Ruby on Rails. The series begins with the introduction and overview of the ideas behind testing.

Unit Testing Classes and Instances

Any Ruby code can be tested with TestUnit. Working with classes and instances of objects is no different. Let’s create definition for a Car class (keeping with the car theme from the last section). Then we can write tests that will test the Car class. We will also spend some time considering what we should test and how we can test it.

(more…)

Testing in Rails: Part 1 - Unit Testing in Ruby

Wednesday, November 14th, 2007

This is part of an ongoing series of posts about how to get started writing tests for Ruby on Rails. The series begins with the introduction and overview of the ideas behind testing.

Unit Testing

Volt gauge

I am going to cover several types of tests over the course of this tutorial: unit tests, functional tests, integration tests. I will start with unit tests. Unit tests are a good way to introduce the subject of testing and, if you already have a working Rails application, they are the first tests you should consider adding. Think of unit tests as our first testing layer, a foundation for the other layers.

Unit testing is a testing technique to validate that individual “units” of code are working properly. A “unit” refers to the smallest testable part of the code. When unit testing, we are not interested in how all the units fit together, just in make sure that each unit is functioning properly on its own.

(more…)

Testing in Rails: Introduction

Saturday, November 10th, 2007

Meter face

For some time, I’ve been wanting to teach how to get started writing tests for Ruby on Rails. Eventually I’d like to do a video training on the subject, but until then I’ve decided to write a series of blog posts as a tutorial.

Everyone agrees that testing is important, yet a small percentage of developers actually write tests. That’s understandable because there is a lot to learn when first starting with Ruby on Rails: installation, Ruby, the MVC framework, Rails, ActiveRecord, migrations, validations, routes, pagination, plug-ins, deployment… There’s more than enough to keep beginners busy during their first few projects. Testing requires learning yet another skill for something that seems like it can be put off until later. After all, you just want to get the site built, right?

Experienced developers often preach to beginners how important it is to test. I’ve even heard it said: “You are not a professional developer unless you write tests.” That is simply not true. You can write great applications, have lots of clients and make lots of money without writing tests. There are thousands of professional developers who don’t. But what I think they really mean by that statement is: Once you start writing tests, you’ll reap a lot of benefits (saving time and writing better code), take your programming to another level, and have a competitive edge over developers who don’t write tests. And who doesn’t want to save time and write better code???

But how do you get there? If you are a Ruby on Rails beginner, focus on the essentials first. Write an application or two. You can start writing tests from the beginning, but I think it’s best if you learn to program in Ruby and have a solid understanding of what Rails is doing first. After you have the fundamentals down, you’ll be ready to learn to write tests. Don’t worry, it’s not as difficult as it might seem. I’m going to walk you through the process step-by-step. (It’ll be an ongoing project spread out over many blog posts.)

(more…)

Ruby on Rails Beyond the Basics

Thursday, October 18th, 2007

RoR BTB package

I’m happy to announce that my latest video training, Ruby on Rails Beyond the Basics, has been released on the lynda.com Online Training Library.

Ruby on Rails Beyond the Basics is the sequel to Ruby on Rails Essential Training and is 11.5 hours of video training for web developers who already feel comfortable with the fundamentals of Ruby and the Rails MVC framework. I teach more of the Ruby language and spend a lot of time on code blocks. Then, using the example of a blog as a project, I show you how to use migrations, demonstrate how to create CRUD that doesn’t simply mimic scaffold, and give you a better understanding of ActiveRecord and some of the pitfalls that often trip up developers. I also cover validations, callbacks, routes, pagination, performance improvements and more.

Ruby on Rails Beyond the Basics is available online as streaming video to subscribers of the lynda.com Online Training Library ($25/month, $250/year, $375/year with exercise files included). It is will also be available as a CD-ROM soon both through lynda.com and Amazon.com.

If you are a beginner, you will be better off if you first start with Ruby on Rails Essential Training which is available online to lynda.com OTL subscribers and on CD-ROM, both through lynda.com and Amazon.com, for $99.95.

If you try either of them and find that they are helpful, be sure to let me know!

Topics include:

  • Updating Ruby, Rails and projects
  • Using irb and the Rails console
  • Intermediate Ruby language techniques
  • Understanding code blocks
  • Catching errors and raising exceptions
  • Using migrations to manage database changes
  • Understanding ActiveRecord and avoiding common pitfalls
  • Creating flexible controllers and views
  • Improving performance with eager loading and cache counters
  • Working with form validations and model callbacks
  • Using partials and helpers to organize views
  • Salting passwords for increased security
  • Choosing how to store session data
  • Understanding and defining custom and named routes
  • Pagination
  • Using plug-ins

Rails version 1.2.5 and Capistrano 2.1

Monday, October 15th, 2007

If you blinked you would have missed version 1.2.4. Rails version 1.2.5 has been released. For the most part, it is a security release to fix a JSON problem. If you aren’t using JSON, then it’s optional but never a bad idea.

If you didn’t upgrade to version 1.2.4 already, don’t be alarmed when gem install rails –include-dependencies downloads version 1.2.5 now.

If you want to upgrade to 1.2.5, you can follow the same steps as I outlined previously for 1.2.4.

And Capistrano 2.1 has been released.

Capistrano is a tool for automating tasks on remote servers, especially those running Ruby on Rails applications. It lets system administrators execute commands and roll back changes in parallel across multiple machines.