Testing is helpful for ensuring that your code runs (driver code). This is to make sure that current features work, old features still work, and future work will be easily tested. By default, every Rails application has three environments: development, test, and production.
Rails offers three kinds of testing:
RSpec is testing tool for the Ruby programming language.
Note: If you have rails 4 you can run a specific version of rails new with ruby rails new _3.2.13_ your_app
Installing rspec with rails is easy and fun! use:
group :development, :test do
gem 'rspec-rails'
gem 'factory_girl_rails'
gem 'faker'
end
please note this won't work unless you have included rake in your gemfile and then run bundle
============
So what did we just install?
The following code is testing the very familiar numberal to arabic in Rspec:
require_relative "numeral_calc.rb"
pairs = [
[1, "I"],
[2, "II"],
[4, "IV"],
[5, "V"],
[6, "VI"],
[7, "VII"],
[9, "IX"],
[10, "X"],
[11, "XI"],
[1982, "MCMLXXXII"]
]
describe "Numeral Function" do
pairs.each do |limit, glyph|
it "should return #{limit} for #{glyph}" do
convert_arabic(glyph).should == limit
end
end
end # Numeral Function
describe "user controller" do
it "should allow a user with passing validation to be created" do
User.create(name: "passing name").should == User.find_by_name("passing name")
end
Be clear about what method you are describing
BAD
describe 'the authenticate method for User' do
describe 'if the user is an admin' do
GOOD
describe '.authenticate' do
describe '#admin?' do
Use contexts
BAD
it 'has 200 status code if logged in' do
response.should respond_with 200
end
GOOD
context 'when logged in' do
it { should respond_with 200 }
end
TBC
require 'spec_helper'
describe Contact do
it "has a valid factory" do
Factory(:contact).should be_valid
end
it "is invalid without a firstname" do
Factory.build(:contact, firstname: nil).should_not be_valid
end
it "is invalid without a lastname" do
Factory.build(:contact, lastname: nil).should_not be_valid
end
it "returns a contact's full name as a string" do
Factory(:contact, firstname: "John", lastname: "Doe").name.should == "John Doe"
end
describe "filter last name by letter" do
before :each do
@smith = Factory(:contact, lastname: "Smith")
@jones = Factory(:contact, lastname: "Jones")
@johnson = Factory(:contact, lastname: "Johnson")
end
context "matching letters" do
it "returns a sorted array of results that match" do
Contact.by_letter("J").should == [@johnson, @jones]
end
end
context "non-matching letters" do
it "does not return contacts that don't start with the provided letter" do
Contact.by_letter("J").should_not include @smith
end
end
end
end
For more information, please visit: http://everydayrails.com/2012/03/19/testing-series-rspec-models-factory-girl.html