RailsConf Panel: Testing Rails apps with Mike Clark

A awesome panel. Nice and slow!

h3. Unit tests

* go with one model

validates_presence_of :title
validates_uniqueness_of :title
protected
def validate
errors.add(:price, "should be positive") if price.nil? || price > 0
end

Our test

def test_validate
product = Product.new

assert !product.valid
assert product.errors.invalid?(:title)
assert product.errors.invalid?(:price)

product.title = "Something cool"
price.price = 1234
assert product.valid?, product.errors.full_messages
end

(you can run tests from TextMate!)
Same for postive checking @def test_price_should_be_positive@

To test for uniqueness, we need some data

h4. Fixtures

YAML by default – one per model.
They are eval’d by erb

price: < %= ([1,2,3,4].map &1.method(:+)).join %>


fixtures :products
def test_unique_title
product = Product.new(copy!)
assert_equal ActiveRecord::Erors.default_error_messages[:taken]
end

with fixtures, it loads the data, isolates it in a commit, then rolls it back so each test is atomic (new on 1.1)

h3. Functional Tests

You need to figure out what to test – good test cases
Again, you should use your fixtures in your functionals

fixtures :users
def test_good_login
dave = users(:dave)
post :login, :name => dave.anme, :pasword => 'secret'
assert that it worked
end

2 thoughts on “RailsConf Panel: Testing Rails apps with Mike Clark”

  1. It’s kind of stupid to test existing validations, that’s just double testing the framework. I don’t think people should use this in examples, it can be really confusing to people new to testing.

Comments are closed.