RSpeck before after

RSpec is a Test Framework for Ruby! And RSpec is just awesome! It is the best Test Framework I know. Add this 2 lines to your Gemfile to the test group and the development group.

gem 'rspec-rails', '2.8.0'
gem 'webrat', '0.7.3'

Webrat is a browser simulator. With RSpec and Webrat you can write integration tests and test the UI of your Web App!

Assume you want to write some specs for a class product. And you need for every spec to create a new product and after the spec to remove it. For this kind of tasks you can use before and after block in rspec.


before(:each) do
  @product = Product.new
end

after(:each) do
  @product.remove
end

So your rspec file maybe looks like this:


require 'spec_helper'

describe Product do

 before(:each) do
   @product = Product.new
 end

 after(:each) do
   @product.remove
 end

 describe "find_by_name" do

   it "returns an empty list. Search term is not in the DB" do
     name = "junitggasgagasgj8623"
     @product.name = name
     @product.prod_key = "gasgagasgj8623_junit/junit"
     @product.save
     results = Product.find_by_name( "sgj8623agajklnb8738gas" )
     results.should_not be_nil
     results.size.should eq(0)
   end

   it "returns an empty list. Search term is an empty string" do
     name = "junitggasgagasgj8623"
     @product.name = name
     @product.prod_key = "gasgagasgj8623_junit/junit"
     @product.save
     results = Product.find_by_name( "" )
     results.should_not be_nil
     results.size.should eq(0)
   end

  end

end

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s