몇 가지 방법을 시도해 보았습니다. 필자가 작성한 사용자 유닛 테스트의 다양한 순열이 왜 파일 유형 테스트에 실패했는지에 대해 명확하지 않습니다. 사용자 객체의 이미지 속성. 여기 Rails RSpec 유닛 테스트가 사용자 속성, 이미지 파일 유형에 실패합니다.
는 ... 내가 현재 가지고있는모델/user.rb
class User < ApplicationRecord
mount_uploader :image, ImageUploader
validate :image_size_validation
validates_format_of :image, with: %r{\.(png|jpg|jpeg)\Z/}i, message: "image must be png, jpg, or jpeg", allow_nil: true
def image_size_validation
errors[:image] << "should be less than 5MB" if image.size > 5.megabytes
end
end
업 로더/image_uploader.rb의
class ImageUploader < CarrierWave::Uploader::Base
def extension_white_list
%w(jpg jpeg gif png)
end
end
사양/모델/user_spec.rb
let(:user) { FactoryGirl.create(:user, username: "zoidberg", image: "image.png") }
it "has a valid image file" do
expect(user).to be_valid
expect(user.image).to be_valid
expect(FactoryGirl.build(:user, username: "Farnsworth", image: "image.jpg")).to be_valid
end
수수께끼의 경우, username: <something>
을 지정하지 않으면 테스트는 Username is invalid
으로 실패합니다. 다른 모든 테스트에서 작동하고 공장에 내장되어 있음에도 불구하고.
사양 나는 또한 내가 일 것이라고 생각하지만 명확하지 않습니다이 it { should have_valid(:image).when('image.jpg', 'image.png', 'image.jpeg')}
을 시도
FactoryGirl.define do
factory :user do
first_name Faker::Name.first_name
last_name Faker::Name.last_name
sequence(:username) { |n| "#{n}#{Faker::Internet.user_name}#{Faker::Number.number(5)}#{Faker::Hipster.word}" }
sequence(:email) { |n| "#{n}#{Faker::Hipster.word}#{Faker::Number.number(5)}#{Faker::Internet.email}" }
phone Faker::Base.numerify('##########')
password Faker::Internet.password(6, 20)
state Faker::Address.state_abbr
city Faker::Address.city
image Faker::Avatar.image
sequence(:zip) { |n| "#{n}#{n}#{n}#{n}#{n}" }
seeking_coach true
accept_email true
accept_phone true
end
end
/공장/user.rb.
'be_valid'는 객체의 속성이 아니라 객체에 사용되도록되어 있습니다. 개체의 이미지를 호출하면 문자열이 아닌 업 로더가 반환되기 때문에 형식 유효성 검사가 수행된다고 생각합니다. –
개체 특성에 적합한 구문은 무엇입니까? –
레일즈는'ActiveRecord :: RecordInvalid : Validation failed : 이미지 이미지는 png, jpg, jpeg 여야합니다 .' –