2012-02-19 65 views
0

如何測試給定的輔助方法只需要一個參數?如何測試RSpec中的參數計數?

我想這樣做的:

describe "#textile" do 
    it "should take only one argument" do 
    textile().should raise_error 
    end 
end 

,但似乎仍然打破了測試,並顯示錯誤wrong number of arguments 0 for 1

+0

爲什麼要測試?無論如何,如果您使用有效的單一參數對其進行測試,並將其定義更改爲更多,則測試將失敗。除非你給第二個參數一個默認值。 – 2012-02-19 01:20:41

回答

1

不管你爲什麼會想測試這一點,這裏有一個方法來寫:

describe "#textile" do 
    it "should fail when given no arguments" do 
    expect { textile() }.to raise_error ArgumentError 
    end 

    it "should accept one argument" do 
    expect { textile("foo") }.not_to raise_error ArgumentError 
    end 
end 

注意,你可以離開關ArgumentError,只是說,這些調用應該或不應該引發錯誤,但通過特別說明他們應該或不應該提出ArgumentError,你正在隔離你想要指定的情況。 textile("foo")可能會引發其他一些異常,但仍會通過第二個示例。

1

實際上,你可以直接測試arity。

>> method(:hello).arity 
=> 2 

,您可以根據這些給定的默認值不同的答案,加上任何*args爲好。

你會想read the documentation描述此:

返回由方法所接受的參數個數的指示。 爲採用固定數量的參數的方法返回一個非負整數。對於帶有可變參數個數的Ruby方法, 返回-n-1,其中n是所需參數的個數。對於用C編寫的方法 ,如果調用採用可變數量的參數 ,則返回-1。

因此,在rspec中,您會相應地編寫測試,測試arity,而不是測試是否引發錯誤。