使用Rspec進行行為驅動測試 :
require 'machine'
describe Machine do #Machine 是要測試的類名
before :each do
@machine=Machine.new([:shopping,:checking_out])
@machine.events = {:checkout =>{:from => :shopping, :to => :checking_out}}
end
it "should initially have a state of the first state" do
@machine.state.should == :shopping
end
it "should remember a list of valid states" do
@machine.states.should == [:shopping, :checking_out]
end
it "should remember a list of events with transitions" do
@machine.events.should == {:checkout => {:from => :shopping, :to => :checking_out}}
end
it "should remember a list of valid states" do
@machine.states = [:shopping, :checking_out]
@machine.states.should == [:shopping,:checking_out]
end
it "should transition to :checking_out upon #trigger(:checkout) event " do
@machine.trigger(:checkout)
@machine.state.should == :checking_out
end
it "should transition to :success upon #trigger(:accept_card)" do
@machine.events = {
:checkout =>
{:from => :shopping,:to => :checking_out},
:accept_card=>
{:from => :checking_out,:to => :success}
}
@machine.trigger(:checkout)
@machine.state.should == :checking_out
@machine.trigger(:accept_card)
@machine.state.should == :success
end
it "should not transition to :success upon #trigger(:accept_card)" do
@machine.events = {
:checkout =>
{:from => :shopping,:to => :checking_out},
:accept_card=>
{:from => :checking_out,:to => :success}
}
@machine.trigger(:accept_card)
@machine.state.should_not == :success
end
end
以下是ruby code:
class Machine
attr_accessor :state ,:events,:states
def initialize(states)
@states = states
@state = @states[0]
end
def trigger(event)
@state = events[event][:to] if state== events[event][:from]
end
end
首先學習Rspec必須先瞭解測試驅動開發(TDD) 和 行為驅動開發(BDD)。
TDD:利用測試來驅動軟體的設計和開發,是極限編程的重要特點,方法主要是,先寫測試程式,然後再通過編碼使其通過測試,他以不斷的測試驅動代碼的開發,這樣即簡化了代碼又保證來軟體的品質。
原理:
BDD:
RSpec 是一門專門用於描述Ruby程式的行為的ruby域指定語言。RSpec讓應用程式的作者能以流暢的語言來表達他們的額設計意圖。
Rspec是一系列行為的集合。這些行為具有對應的執行個體。
下面簡要介紹Rspec 使用
1.should和預期情況
@variable.should be valid
@var.should == expected
@var.should ===expected
@var.should =~ regexp
2.結果預測
target.should be_true
target.should be_nil
target.should_not be_nil
target.should be_empty
target.should be_an_instance_of(Fixnum)
target.should be_a_kind_of(Fixnum)
target.should have_key(:key)
{:foo=>"foo"}.should have_key(:foo)
[1,2,3,4,5].should include(1)
[1,2,3,4,5].should have(5).items
3.支援自訂的斷言方法
實現步驟:
一:定義類 class WhatEver,
二:實現
1. initialize(expected)
2.matches?(actual)
3.failure_message
4.negative_failure_message
5.description
三:
在你的spec所包含的模組中,加入
def be_finished(expected)
WhatEver.new(expected)
end
四:調用
bob.should be_finished(x)
4.共用的行為
1.before(:all)
2.before(:each)
3.after(:each)
4.after(:all)
5.所有預期的情況
6.各種包含入的模組
可以通過:shared=>true 來定義共用行為
---待續
5.RSpec的資料類比和佔位代碼
---待續