2011-04-13 28 views
3

我有一幫非常重複RSpec的測試,都具有相同的格式:如何在Rspec中進行一次沒有Shoulda的線路測試?

it "inserts the correct ATTRIBUTE_NAME" do 
    @o.ATTRIBUTE_NAME.should eql(VALUE) 
end 

這將是很好,如果我可以只讓一條線測試,如:

compare_value(ATTRIBUTE_NAME, VALUE) 

但早該沒有按」似乎是面向這些類型的測試。還有其他的選擇嗎?

+0

難道你不能把它們放在單個'it'塊中,並且對每個屬性使用'.should =='? – Dogbert 2011-04-13 23:51:34

回答

3

如果你想讓它更清楚地閱讀和只有1號線我會寫一個自定義的RSpec的幫手。假設我們有下面的類,我們要測試:

class MyObject 
    attr_accessor :first, :last, :phone 

    def initialize first = nil, last = nil, phone = nil 
    self.first = first 
    self.last = last 
    self.phone = phone 
    end 
end 

我們可以編寫以下匹配:

RSpec::Matchers.define :have_value do |attribute, expected| 
    match do |obj| 
    obj.send(attribute) == expected 
    end 

    description do 
    "have value #{expected} for attribute #{attribute}" 
    end 
end 

然後寫我們可以做類似的測試:

describe MyObject do 
    h = {:first => 'wes', :last => 'bailey', :phone => '111.111.1111'} 

    subject { MyObject.new h[:first], h[:last], h[:phone] } 

    h.each do |k,v| 
    it { should have_value k, v} 
    end 
end 

如果你把所有這些放在一個文件中調用matcher.rb並運行,輸出如下:

> rspec -cfn matcher.rb 

MyObject 
    should have value wes for attribute first 
    should have value bailey for attribute last 
    should have value 111.111.1111 for attribute phone 

Finished in 0.00143 seconds 
3 examples, 0 failures 
+0

你搖滾。謝謝。 – 2011-04-14 15:51:16

+0

@Jeremy Smith不客氣! – Wes 2011-04-14 17:44:33

-1
subject { @o } 
it { attribute.should == value } 
+0

我不得不使用subject.attribute.should ==值。這是必要的還是我做錯了什麼? – 2011-04-14 01:13:57

0

我發現這個偉大的工程:

specify { @o.attribute.should eql(val) } 
11

有時我很遺憾將subject作爲最終用戶設備。據介紹,以支持擴展(如shoulda的匹配),所以你可以這樣寫的例子:

it { should do_something } 

像這樣的例子,但是,不讀得好:

it { subject.attribute.should do_something } 

如果你要使用subject明確,然後在本例中明確地引用它,我建議使用specify代替it

specify { subject.attribute.should do_something } 

底層的語義是相同的,但是這個^^可以被朗讀。

相關問題