2011-10-20 15 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

共有の例を書いていると、ここでは過剰な感じがします。このような状況には、共有される例が1回だけ適用される場面があります。したがって、それらの共有された例は全く共有されません。 –

+0

共有されたサンプルがグローバルに保持されていなかった場合は、それらを使用すると言いますが、(少なくとも前回チェックしたとき)そうではないので、少し過度のことです。 –

関連する問題