2014-04-03 5 views
5

RSpec을 사용하여 DRY이고 양수 및 음수의 경우에 사용할 수있는 shared_examples 그룹을 작성하려면 어떻게해야합니까? 긍정적 인 경우에 작동 shared_examples의Rspec : 양수 및 음수 DRY 공유 예제

예 : it_should_not_behave_like 같은 it_should_behave_like의 반대 뭔가가 있다면

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 

, 즉 큰 것. 이 예문이 유연해야한다는 것을 이해합니다.

+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 

내가 그 방법을 추출하거나 실제 예를 정당화 할만큼 복잡 된 모든 않는 한에서 공유 예제를 사용하지 않을 것입니다.

관련 문제