2014-02-24 74 views
0

我是編寫自定義匹配器的新手,並且大多數示例都涵蓋了非常簡單的設置。編寫一個從具有參數的模塊擴展函數的匹配器的正確方法是什麼?我是否需要給實際塊的函數參數input?謝謝。函數參數的RSpec匹配器

# My Example: 
RSpec::Matchers.define :total do |expected| 
    match do |input, actual| 
    actual.extend(Statistics).sample(input) == expected 
    end 
end 

# Before: 
describe Statistics do 
    it 'should not be empty' do 
    expect(Statistics.sample(input)).not_to be_empty 
    end 
end 

回答

2

那麼它取決於你要測試的。如果你只是想測試該模塊包含一個方法,也許是這樣的:

module Statistics 
    def sample 
    end 
end 

class Test 
end 

RSpec::Matchers.define :extend_with do |method_name| 
    match do |klass| 
    klass.extend(Statistics).respond_to?(method_name) 
    end 
end 

describe Statistics do 
    subject { Test.new } 
    it { should extend_with(:sample) } 
end 

如果你想測試返回值,你可以添加作爲參數,或鏈的匹配:

module Statistics 
def sample(input) 
    41 + input 
    end 
end 

class Test 
end 

RSpec::Matchers.define :extend_with do |method_name, input| 
    match do |klass| 
    @klass = klass 
    @klass.extend(Statistics).respond_to?(method_name) 
    end 
    chain :returning_value do |value| 
    @klass.extend(Statistics).__send__(method_name, input) == value 
    end 
end 

describe Statistics do 
    subject { Test.new } 
    it { should extend_with(:sample) } 
    it { should extend_with(:sample, 2).returning_value(43) } 
end 

匹配器DSL非常靈活。您不必掛上「」中的「實際」和「預期」命名的命名 - 編寫規格說明,以便告訴您的代碼故事。

+0

優秀的答案。對於這個規範,我只是想能夠通過輸入來調用我的方法示例。那麼,而不是respond_to?我會打電話給樣品(輸入)。輸入表示一個被轉換爲數組的字符串。所以我想能夠這樣調用它:'''expect('10,20,30')。to sum_up_to(60.0)'''另外,me模塊只是類方法。 – theGrayFox