Too Cool for Internet Explorer

Sunday, March 16, 2008

Ruby from Test::Unit to RSpec part 3 of 3 b

The second part of this article, is about the Spec framework, the one that give Rspec the original name.

After the customer and the developer agree, over a Story describing the business behavior, is time to go on with a more techical specification.

The Spec framework provides RSpec a Domain Specific Language with which you can express executable examples of the expected behaviour of a system.

Thinking about the grading process, we need to describe our process behaviour, so the initial structure will be like this:


require 'spec'
require 'grading'

describe Grading do
...
end

Now, to describe the behaviour, use the folowing sample structure:

1 - To stablish states, of the involved objects.

before(:each) do
(1..9).each { |i| @stack.push i }
@last_item_added = 9
end

2 - RSpec adds "should" and "should_not" methods to any application object.

@student.grade.should ...
post.should_not ...

3 - And a "expectations" set.

be_...(...)
have(...).(...)
raise_error(...)

All together now…

# grading_spec.rb
require 'spec'
require 'grading'

describe Grading do
GradingOverflowError = '123'
before(:each) do
@grading = Grading.new
end

it "should score more then 50 to pass" do
@grading.score(51) == 51
@grading.status('pass').should == 'pass'
end

it "should complain when score more then 100" do
lambda { @grading.score(101) }.should raise_error(GradingOverflowError)
end
end

# grading.rb
class Grading
def score(grade)
if grade > 100
raise '123'
end
end

def status(status)
@status = status
end
end

To run this specification, use this command:

ruby grading_spec.rb --format specdoc

And should get the following result

Grading
- should score more then 50 to pass
- should complain when score more then 100

Finished in 1.219 seconds

2 examples, 0 failures

Now try to add this specification:

it "should get status 'pass' to be assigned to next batch" do
@grading.status('pass') == 'pass'
@grading.assign_batch('pass').should == 3
end

And try to get this result:

Grading
- should score more then 50 to pass
- should complain when score more then 100
- should get status 'pass' to be assigned to next batch

Finished in 0.875 seconds

3 examples, 0 failures

Now start RSpec in practice on the next project.

1 comment:

Blaxter said...

Thanks for this post series, they've been very useful for me, there are a lot of stuff about rspec but your post are a very good point to start, at least the best I found :)