RSpec in 15 Minutes

Cliff Rhyne 4/3/08

Overview
RSpec Setup Spec Structure Scaffold Generation Next Steps

RSpec Setup

RSpec Setup
Gem Installation:

$ gem install rspec

Enables RSpec use by textpad and third party gems

RSpec Setup (continued)
Plugin Installation:
$ script/plugin install http://rspec.rubyforge.org/svn/tags/CURRENT/rspec $ script/plugin install http://rspec.rubyforge. org/svn/tags/CURRENT/rspec_on_rails

Generate RSpec project scaffolding:
$ script/generate rspec

RSpec Setup (continued)

Manually run RSpec tests: $ rake

Spec Structure

Spec Structure
describe "handling GET /snowmen" do   before(:each) do     @snowman = mock_model(Snowman)     Snowman.stub!(:find).and_return([@snowman])   end   it "should be successful" do     get :index     response.should be_success   end end

Spec Structure (continued)
describe "handling GET /snowmen" do ....... end describe method combines individual specs together These can be nested to combine multiple groups of specs

Spec Structure (continued)
before(:each) do   @snowman = mock_model(Snowman)   Snowman.stub!(:find).and_return([@snowman]) end before and after methods setup and tear-down the test The :each symbol specifies this to be run before each spec in the group; replacing it with :all makes it run once before the group. stub! spoofs the method call find and returns the object @snowman

Spec Structure
it "should be successful" do   get :index   response.should be_success end Description in "" should briefly say what is being tested be_success will try to run the success? method in the response object. should checks that success? returns true.

Scaffold Generation

Scaffold Generation
$ script/generate rspec_scaffold Snowman name:string Generates scaffolding and rspec tests for models, controllers, views, and helpers. Controller and model specific generation using rspec_controller and rspec_model.

Scaffold Generation (continued)
Example model spec: describe Snowman do   before(:each) do     @snowman = Snowman.new   end   it "should be valid" do     @snowman.should be_valid   end end

Next Steps

Next Steps

Check out the RSpec website at http://rspec.info

Install and configure ZenTest to automatically run RSpec tests in the background while you work.