2011-05-27 5 views
8

मैं एक साझा उदाहरण समूह बनाकर अपनी चश्मा DRY रखने की कोशिश कर रहा हूं जो सभी व्यवस्थापक नियंत्रकों के लिए बॉयलरप्लेट चेक करता है (Admin मेरे प्रोजेक्ट के नेमस्पेस के तहत सभी नियंत्रक)। मैं यह समझने के लिए संघर्ष कर रहा हूं कि इसे कैसे किया जाए, क्योंकि साझा उदाहरण को जानकारी और पैरामीटर का उपयोग करने के बारे में जानकारी प्रदान करने की आवश्यकता है। यदि परीक्षण विफल रहता है तो इसे आदर्श रूप से सार्थक त्रुटियां प्रस्तुत करनी चाहिए (यानी उस परीक्षण के विवरण को शामिल करें जो वह परीक्षण कर रहा था)।RSpec 2 में साझा उदाहरणों को गतिशील रूप से उत्पन्न करना?

require 'spec_helper' 

shared_examples "an admin controller" do 

    before(:each) do 
    @non_admin = User.make 
    @admin = User.make(:admin) 
    end 

    context "as an admin user" do 
    @actions.each do |action, params| 

     specify "I should be able to access ##{action.last} via #{action.first}" do 
     self.active_user = @admin 
     send(action.first, action.last, params) 

     response.status.should be_ok 
     end 

    end 
    end 

    context "as a regular user" do 
    @actions.each do |action, params| 

     specify "I should be denied access to ##{action.last}" do 
     self.active_user = @non_admin 
     send(action.first, action.last, params) 

     response.status.should be 403 
     end 

    end 
    end 

end 

describe Admin::UserNotesController do 

    @user = User.make 
    @actions = { [:get, :index] => { :user_id => @user.id }, 
       [:get, :new]  => { :user_id => @user.id }, 
       [:post, :create] => { :user_id => @user.id } } 

    it_behaves_like "an admin controller" 

end 

स्पष्ट कारण यह है कि @actions साझा उदाहरण समूह को दिखाई नहीं देता के लिए यह त्रुटियों। अगर मैं let का उपयोग करता हूं, तो यह केवल उदाहरण के संदर्भ में उपलब्ध है, न कि describe ब्लॉक के संदर्भ में। कोई विचार?

उत्तर

27

यहाँ एक अधिक स्वच्छ तरीका है कि काम करना चाहिए है:

require 'spec_helper' 

shared_examples "an admin controller" do |actions| 
    context "as an admin user" do 
    actions.each_pair do |action, verb| 
     specify "I should be able to access ##{action} via #{verb}" do 
     send(verb, action, :user_id => User.make(:admin).id) 
     response.status.should be_ok 
     end 
    end 
    end 

    context "as a regular user" do 
    actions.each_pair do |action, verb| 
     specify "I should be denied access to ##{action}" do 
     send(verb, action, :user_id => User.make.id) 
     response.status.should be 403 
     end 
    end 
    end 
end 

describe Admin::UserNotesController do 
    it_behaves_like "an admin controller", { 
    :index => :get, 
    :new => :get, 
    :create => :post 
    } 
end 

अधिक जानकारी

+1

के लिए http://relishapp.com/rspec/rspec-core/v/2-6/dir/example-groups/shared-examples देखें यह शानदार है, धन्यवाद! कोड हटाने जैसे कुछ भी नहीं है :) – d11wtq

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