2011-10-20 32 views
3

如何重用這些示例,以便僅覆蓋嵌套上下文上的細節?嵌套的Rspec上下文中的繼承示例

像這樣的東西(我用thee,而不是它表示,它是在嵌套上下文中執行它不是RSpec的,我想要什麼。):

describe "Abilities" do 
    subject { Abilities.new user } 

    context "allowed" do 
    let(:user) { Factory(:power_user) } 
    thee { should be_able_to :create, object } 
    thee { should be_able_to :read, object } 
    thee { should be_able_to :update, object } 

    context "comment" do 
     let(:object) { Factory(:comment) } 
    end 

    context "post" do 
     let(:object) { Factory(:post) } 
    end 

    context "blog" do 
     let(:object) { Factory(:blog) } 
    end 

    end 
end 

這個例子最終會與3 3個上下文(評論,帖子,博客)的示例(創建,讀取,更新),總共產生了9個示例。

它是如何實現它(不寫共享示例)?

回答

5

沒有繼承實例的方式,但你可以做一個類的方法:

describe "Abilities" do 
    subject { Abilities.new user } 

    def self.should_allow_stuff 
    it { should be_able_to :create, object } 
    it { should be_able_to :read, object } 
    it { should be_able_to :update, object } 
    end 

    context "allowed" do 
    let(:user) { Factory(:power_user) } 

    context "comment" do 
     let(:object) { Factory(:comment) } 
     should_allow_stuff 
    end 

    context "post" do 
     let(:object) { Factory(:post) } 
     should_allow_stuff 
    end 

    context "blog" do 
     let(:object) { Factory(:blog) } 
     should_allow_stuff 
    end 

    end 
end 

你可以,如果你喜歡在必要時進行重構。

+0

注意:我不推薦這種共享示例的方式。 RSpec中的共享上下文現在存在於上下文中,並且不會流入全局範圍,因此您應該使用它們。或者,因爲共享示例可能會讓人混淆,難以獨立運行,所以我會考慮構建自己的匹配器。 –

1

爲什麼你不想寫共享的例子?這正是他們想要的。

+0

寫共享示例在這裏感覺像是過度殺傷。像這樣的情況有很多,共享示例只能應用一次。因此,這些共享示例根本不共享。 –

+0

如果共享示例沒有全局保存,那麼我會說使用它們,但由於它們不是(至少上次我檢查過),我同意它們有點矯枉過正。 –