2012-02-16 2 views
22

그래서 Rails 3.2 앱을 통해 많은 분야에서 attr_accessibleattr_protected을 설정했습니다. 현재로서는이 필드가 보호되는지 실제로 테스트하지 않습니다. RSpec에서 attr_accessible 필드를 테스트하는 방법

그래서 좀 답변을 구글로 결정하고이 솔루션 우연히 :

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 } 

누구든지이 문제에 대해 더 좋은 해결책을 가지고 있는가? 나는 비슷한 뭔가를 찾고 한 후 내가 했어야 - 정규의 allow_mass_assigment_of에 대해 들었다

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

[Permitters]의 사용을 고려 (https://github.com/permitters/permitters) (attr_accessible + attr_protected) 대신 [Strong Parameters] (https://github.com/rails/strong_parameters)를 사용하십시오. –

+1

이미 프로덕션 환경에서 사용하고 있습니다. 이것은 ForbiddenAttributes가 주류가 아니었던 때였습니다. – WarmWaffles

답변

32

당신은 확인할 수 있습니다. 결국 사용자 정의 matcher를 만들지 않고 저를 위해 일하게되었습니다.

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

희망이 있으면 다른 사람에게 도움이됩니다.

+0

쿨! 이 코드는 어디에 넣으시겠습니까? – emrass

+4

예 : – shingara

+0

에 의해이 코드를'spec/support/be_accessible_matcher.rb'에 넣을 수 있습니다. 왜 배열 – WarmWaffles

27

속성이 #accessible_attributes 목록에 있는지

+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

이것은 새로운 기대 스타일로가는 길입니다. –

관련 문제