Rails에서 문제를 테스트하는 방법
메서드 Personable
가있는 Rails 4 애플리케이션에 문제 가 있다는 점을 감안할 때 full_name
RSpec을 사용하여이를 테스트하려면 어떻게해야합니까?
관심사 /personable.rb
module Personable
extend ActiveSupport::Concern
def full_name
"#{first_name} #{last_name}"
end
end
발견 한 방법은 확실히 약간의 기능을 테스트하는 데는 효과가 있지만 매우 취약 해 보입니다. 더미 클래스 (실제로는 Struct
솔루션에 포함되어 있음)가 include
관심사 인 실제 클래스처럼 동작 할 수도 있고 그렇지 않을 수도 있습니다 . 또한 모델 문제를 테스트하려는 경우 그에 따라 데이터베이스를 설정하지 않는 한 객체의 유효성을 테스트하거나 ActiveRecord 콜백을 호출하는 등의 작업을 수행 할 수 없습니다 (더미 클래스에 데이터베이스 테이블 백업이 없기 때문). 그것). 또한 우려 사항을 테스트 할뿐만 아니라 모델 사양 내에서 우려 사항의 동작을 테스트하고 싶을 것입니다.
그렇다면 한 돌로 두 마리의 새를 죽이는 것은 어떨까요? RSpec에의 사용에 의해 공유 예를 들어 그룹을 , 당신은 그들 (예를 들어, 모델)을 사용하여 실제 수업에 대한 우려를 테스트 할 수 있습니다 그리고 당신은 그들이 사용하고 사방을 테스트 할 수 있습니다. 그리고 테스트를 한 번만 작성하고 관심사를 사용하는 모델 사양에 포함하면됩니다. 귀하의 경우에는 다음과 같이 보일 수 있습니다.
# app/models/concerns/personable.rb
module Personable
extend ActiveSupport::Concern
def full_name
"#{first_name} #{last_name}"
end
end
# spec/concerns/personable_spec.rb
require 'spec_helper'
shared_examples_for "personable" do
let(:model) { described_class } # the class that includes the concern
it "has a full name" do
person = FactoryBot.build(model.to_s.underscore.to_sym, first_name: "Stewart", last_name: "Home")
expect(person.full_name).to eq("Stewart Home")
end
end
# spec/models/master_spec.rb
require 'spec_helper'
require Rails.root.join "spec/concerns/personable_spec.rb"
describe Master do
it_behaves_like "personable"
end
# spec/models/apprentice_spec.rb
require 'spec_helper'
describe Apprentice do
it_behaves_like "personable"
end
이 접근 방식의 장점은 AR 콜백 호출과 같은 작업을 시작할 때 훨씬 더 분명해집니다. AR 객체보다 적은 것은 수행하지 않습니다.
내가받은 댓글에 대한 응답으로 내가 한 일은 다음과 같습니다 (개선 사항이 있으면 언제든지 게시 해주세요) .
spec / concerns / personable_spec.rb
require 'spec_helper'
describe Personable do
let(:test_class) { Struct.new(:first_name, :last_name) { include Personable } }
let(:personable) { test_class.new("Stewart", "Home") }
it "has a full_name" do
expect(personable.full_name).to eq("#{personable.first_name} #{personable.last_name}")
end
end
Another thought is to use the with_model gem to test things like this. I was looking to test a concern myself and had seen the pg_search gem doing this. It seems a lot better than testing on individual models, since those might change, and it's nice to define the things you're going to need in your spec.
참고URL : https://stackoverflow.com/questions/16525222/how-to-test-a-concern-in-rails
'program tip' 카테고리의 다른 글
Ruby를 사용하여 한 단계로 배열을 초기화하는 방법은 무엇입니까? (0) | 2020.08.23 |
---|---|
자바 스크립트로 업로드하기 전에 이미지 너비와 높이를 확인하세요. (0) | 2020.08.23 |
Tensorflow에서 그래프의 모든 Tensor 이름을 가져옵니다. (0) | 2020.08.23 |
FileUpload 서버 컨트롤을 사용하지 않고 ASP.net에서 파일 업로드 (0) | 2020.08.23 |
Hamcrest 비교 컬렉션 (0) | 2020.08.23 |