2012-02-16 12 views
22

में attr_accessible फ़ील्ड का परीक्षण कैसे करें, इसलिए हम अपने रेल 3.2 एप के माध्यम से कई क्षेत्रों में attr_accessible और attr_protected सेट अप कर रहे हैं। अभी के लिए हम वास्तव में यह सुनिश्चित करने के लिए परीक्षण नहीं करते कि ये फ़ील्ड सुरक्षित हैं।आरएसपीसी

तो मैं कुछ जवाब गूगल का फैसला किया और इस समाधान पर ठोकर खाई:

RSpec::Matchers.define :be_accessible do |attribute| 
    match do |response| 
    response.send("#{attribute}=", :foo) 
    response.send("#{attribute}").eql? :foo 
    end 
    description { "be accessible :#{attribute}" } 
    failure_message_for_should { ":#{attribute} should be accessible" } 
    failure_message_for_should_not { ":#{attribute} should not be accessible" } 
end 

लेकिन इस समाधान केवल परीक्षण के अगर विधि प्रतिक्रिया दे रहा है देखने के लिए। मुझे जो चाहिए वह परीक्षण करने के लिए एक तरीका है कि गुणों को बड़े पैमाने पर असाइन किया जा सकता है और नहीं किया जा सकता है। मैं ईमानदारी से वाक्यविन्यास

it { should_not be_accessible :field_name } 
it { should be_accessible :some_field } 

क्या किसी के पास इस समस्या का बेहतर समाधान है?

+0

[Permitters] उपयोग करने पर विचार (https://github.com/permitters/permitters) या [मजबूत पैरामीटर्स] (https://github.com/rails/strong_parameters) बड़े पैमाने पर असाइनमेंट सुरक्षा (attr_accessible + attr_protected) के बजाय, जो रेल 4 में जा रहा है। –

+1

पहले से ही उत्पादन में इसका उपयोग कर रहा है। यह तब से कुछ था जब ForbiddenAttributes मुख्यधारा नहीं था। – WarmWaffles

उत्तर

32

आप देख सकते हैं विशेषता #accessible_attributes सूची में है

RSpec::Matchers.define :be_accessible do |attribute| 
    match do |response| 
    response.class.accessible_attributes.include?(attribute) 
    end 
    description { "be accessible :#{attribute}" } 
    failure_message_for_should { ":#{attribute} should be accessible" } 
    failure_message_for_should_not { ":#{attribute} should not be accessible" } 
end 
+0

कूल! आप यह कोड कहां रखेंगे? – emrass

+4

आप इस कोड को 'spec/support/be_accessible_matcher.rb' में डाल सकते हैं उदाहरण के द्वारा – shingara

+0

अब मुझे लगता है कि उस सरणी – WarmWaffles

27

मैं कुछ इसी तरह की तलाश में गया था और तब मैं चाहिये-मेल खाने allow_mass_assigment_of के बारे में बताया गया था। यह कस्टम मैचर बनाने के बिना मेरे लिए काम करना समाप्त हो गया।

it { should allow_mass_assignment_of :some_field } 
it { should_not allow_mass_assignment_of :field_name } 

उम्मीद है कि यह किसी और की मदद करेगा।

+0

चाहते हैं तो यह ऊपर या नीचे लागू किया गया है, यह अनुमान लगाया जाएगा। हालांकि, मुझे यह अस्तित्व में नहीं पता था। आपके लिए वोट – WarmWaffles

+1

बस जोड़ने के लिए, मणि से लिंक करें: https://github.com/thoughtbot/shoulda-matchers –

1

किसी कारण RSpec मेरा आप कुछ इस तरह कर सकते हैं किया गया था की तरह ऊपर juicedM3 के जवाब पर ट्रिपिंग है के लिए हैं:

specify { expect { Model.new(unaccessible_attr: value) }.to raise_error(ActiveModel::MassAssignmentSecurity::Error) } 
+0

यह नई उम्मीद शैली के साथ जाने का तरीका है। –