以下代码在带有 RSpec 3.5 和Shrine gem的 Rails 4.2 应用程序的模型规范中测试图像验证以进行文件上传。
我的问题是:
- 您能想出一种改进以下测试的方法或更好的方法来测试这些验证吗?
- 如何提高文件大小验证测试的速度?如果可能的话,我想对其进行测试,而无需实际上传 >10mb 的文件。
文件上传设置的其他方面在控制器和功能规范中进行了测试,这与这个问题无关。
RSpec.describe ShareImage, :type => :model do
describe "#image", :focus do
let(:image_file) do
# Could not get fixture_file_upload to work, but that's irrelevant
Rack::Test::UploadedFile.new(File.join(
ActionController::TestCase.fixture_path, 'files', filename))
end
let(:share_image) { FactoryGirl.build(:share_image, image: image_file) }
before(:each) { share_image.valid? }
context "with a valid image file" do
let(:filename) { 'image-valid.jpg' }
it "attaches the image to this record" do
expect(share_image.image.metadata["filename"]).to eq filename
end
end
context "with JPG extension and 'text/plain' media type" do
let(:filename) { 'image-with-text-media-type.jpg' }
it "is invalid" do
expect(share_image.errors[:image].to_s).to include("invalid file type")
end
end
# TODO: Refactor the following test (it takes ~50 seconds to run)
context "with a >10mb image file" do
let(:filename) { 'image-11mb.jpg' }
it "is invalid" do
expect(share_image.errors[:image].to_s).to include("too large")
end
end
end
end