2014-04-03 29 views
5

使用RSpec,我該如何編寫一組DRY爲空的shared_examples,可用於正面和負面情況?Rspec:DRY正例和負例的共享示例

shared_examples的例子,對於陽性病例的工作原理:

shared_examples "group1" do 
    it "can view a person's private info" do 
    @ability.should be_able_to(:view_private_info, person) 
    end 
    # also imagine I have many other examples of positive cases here 
end 

如果有什麼東西it_should_behave_like相反,像it_should_not_behave_like,那簡直太好了。我知道這個例子的文本必須是靈活的。

+0

我一直在想這個好幾個月。我不認爲這是可以做到的,但也許是最好的。規格可能非常難以遵循。 – Starkers

回答

0

你可以做這樣的:

類測試:

class Hat 
    def goes_on_your_head? 
    true 
    end 

    def is_good_to_eat? 
    false 
    end 

end 

class CreamPie 
    def goes_on_your_head? 
    false 
    end 

    def is_good_to_eat? 
    true 
    end 

end 

例子:

shared_examples "a hat or cream pie" do 
    it "#{is_more_like_a_hat? ? "goes" : "doesn't go" } on your head" do 
    expect(described_class.new.goes_on_your_head?).to eq(is_more_like_a_hat?) 
    end 

    it "#{is_more_like_a_hat? ? "isn't" : "is" } good to eat" do 
    expect(described_class.new.is_good_to_eat?).to eq(!is_more_like_a_hat?) 
    end 

end 

describe Hat do 
    it_behaves_like "a hat or cream pie" do 
    let(:is_more_like_a_hat?) { true } 
    end 
end 

describe CreamPie do 
    it_behaves_like "a hat or cream pie" do 
    let(:is_more_like_a_hat?) { false } 
    end 
end 

我將不太可能做到這一點在真正的代碼,因爲它會很難寫出可理解的例子描述。相反,我會想辦法讓兩個共享的例子,並提取到重複數據刪除方法:

def should_go_on_your_head(should_or_shouldnt) 
    expect(described_class.new.goes_on_your_head?).to eq(should_or_shouldnt) 
end 

def should_be_good_to_eat(should_or_shouldnt) 
    expect(described_class.new.is_good_to_eat?).to eq(should_or_shouldnt) 
end 

shared_examples "a hat" do 
    it "goes on your head" do 
    should_go_on_your_head true 
    end 

    it "isn't good to eat" do 
    should_be_good_to_eat false 
    end 

end 

shared_examples "a cream pie" do 
    it "doesn't go on your head" do 
    should_go_on_your_head false 
    end 

    it "is good to eat" do 
    should_be_good_to_eat true 
    end 

end 

describe Hat do 
    it_behaves_like "a hat" 
end 

describe CreamPie do 
    it_behaves_like "a cream pie" 
end 

當然我不會提取這些方法,甚至,除非是實際的例子是複雜的,足以證明它使用共享的例子。