Rails 튜토리얼을 따라가는 작은 애플리케이션을 만들고 있습니다. Michael Hartl이 기술을 익히고 있습니다.모델의 백분율 속성을 테스트하는 RSpec Custom Matcher
글쎄, 나를위한 가장 큰 어려움은 TDD ... 나는 그것에 익숙해지기 시작했다. 그러나이 시점에서 나는 약간의 문제에 직면한다 : 나의 모델 중 하나가 많으면 나는 반복적 인 테스트를 많이 가진다. 속성은 백분율입니다.
describe Measure do
let(:user) { FactoryGirl.create(:user) }
before do
@measure = user.measures.build(
fat: 35.0,
water: 48.0,
muscle: 25.5,
bmi: 33.0
)
end
subject { @measure }
describe 'validations' do
describe 'percentage attributes validations' do
percentages = %w[bmi fat muscle water]
percentages.each do |percentage|
describe "#{percentage} should be a number" do
before { @measure.send("#{percentage}=".to_sym, 'value') }
it { should_not be_valid }
end
end
percentages.each do |percentage|
describe "#{percentage} should be positive" do
before { @measure.send("#{percentage}=".to_sym, -1) }
it { should_not be_valid }
end
end
percentages.each do |percentage|
describe "#{percentage} should be less or equal to 100" do
before { @measure.send("#{percentage}=".to_sym, 100.01) }
it { should_not be_valid }
end
end
end
end
end
그러나 다시이 매우 길고 나는 RSspec 사용자 정의 Matcher를 될 수있는 레일 자습서의 8 장에서 소개하고 생각했다대로
나는 모델 사양 파일에서 이러한 속성에 대한 테스트를 리팩토링 좋은 아이디어. 테스트가be_a_percentage
사용자 정의 Matcher를이
describe 'percentage attributes validations' do
its(:bmi) { should be_a_percentage }
end
처럼 쓸 수 있었던 것처럼
그래서 나는 느꼈다. 그러나 나는 지금까지 내가 가지고 ... 내가 그것을 구현하는 방법을하지 않는 붙어입니다 :RSpec::Matchers.define :be_a_percentage |percentage| do
match |measure| do
# What should I do ?
# percentage is nil and number is the attribute value
# I can't call be_valid on the Measure object
end
end
은 내가 정의 매처 (matcher)가 체인하지만 난에 대한 것들을 읽어
describe 'percentage attributes validations' do
specify { @measure.bmi.should be_a_percentage }
end
다른 전화를 시도 그것을 얻지 마십시오.
이것은 내 첫 번째 게시물, 그것은 긴, 그래서 크기의 코드베이스 증가 당신이 할 수 있습니다
내가이 건조 될 수 확신 그러나 이것은 지금까지 내가 갈 수있다 바로 지금 –
답장과 건의안 제안에 감사드립니다. 커스텀 정규 표현식 질문에 대한 이유는이 'behave_like'는 커스텀 정규 표현자를 한 번만 사용하기 때문에 백분율을 가진 모든 모델 테스트에서 반복되어야한다는 것입니다. –