Saturday, May 12, 2007

learning test/spec




I'm starting to develop my tests with test/spec, which I really like, it makes doing BDD work really well with Ruby on Rails. It's a learning process, and I thought I would share some of it with you.

For one of my sites, telepathytest.com, I have a Sender class (a Sender is the one in the telepathy experiment who tries to telepathically "send" the symbol they are looking to the other person). Anywho, I had to test two of my Sender methods, which were:


# == Schema Information
# Schema version: 5
#
# Table name: senders
#
# id :integer(11) not null, primary key
# ip_address :string(255)
# idhash :string(255)
# created_at :datetime
# last_alive :datetime
# last_symbol_index :integer(11)
# receiver_id :integer(11)
# user_id :integer(11)
# symbols_sent :string(255)
# state :string(255)
# archived :boolean(1)
#
class Sender < ActiveRecord::Base
belongs_to :user
has_one :telepathy_test

before_create :generate_idhash
before_create :generate_test

def generate_idhash
write_attribute "idhash", rand(0xffffffffffffffff).to_s(16)
end

# Generate the 10 symbols to be guessed, these are represented by
# integers between 1 and 5
NUM_SYMBOLS = 10
NUM_SYMBOL_TYPES = 5

def generate_test
symbol_string = ""
NUM_SYMBOLS.times do
symbol = rand(NUM_SYMBOL_TYPES) + 1
symbol_string += symbol.to_s
end
end


The specs that I came up with were:


context "Adam sender" do

fixtures :senders

setup do
@adam = senders(:adam)
@adam.generate_idhash
@adam.generate_test
end

specify "id hash should be between 0 and 0xffffffffffffffff" do
@adam.idhash.to_i(16).should.be > 0
@adam.idhash.to_i(16).should.be < 0xffffffffffffffff
end

specify "total number length of symbols_sent should be NUM_SYMBOLS" do
@adam.symbols_sent.size.should.be Sender::NUM_SYMBOLS
end

specify "all symbols in symbols_sent should be in the range of 0..NUM_SYMBOL_TYPES" do
@adam.symbols_sent.each_byte { |c|
c.chr.to_i.should.be >= 1
c.chr.to_i.should.be <= Sender::NUM_SYMBOL_TYPES
}
end
end


And my fixtures file was really simple:


adam:
id: 1
bob:
id: 2