2014-04-03 7 views
5

आरएसपीसी का उपयोग करके, मैं 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 

बेशक मैं उन तरीकों को अलग नहीं हैं या यहां तक ​​कि सभी जब तक वास्तविक उदाहरण यह औचित्य साबित करने के लिए पर्याप्त जटिल कर रहे थे पर साझा उदाहरण का उपयोग करें।

संबंधित मुद्दे