Paperclip + RSpec:content_typevalidation
我在我的Rails应用程序中使用Paperclip
来附加images
。 我在我的模型中声明了对content_type
validation
validates_attachment :image, :content_type => { :content_type => ["image/jpg", "image/gif", "image/png"] }
我有两个例子,一个是有效图像,另一个是图像无效
对于无效图像,我只是将.txt
文件重命名为.png
it "Image is valid" do image = File.new("#{Rails.root}/spec/support/right.png") expect(FactoryGirl.build(:pin, image: image)).to be_valid end it "Image is invalid" do image = File.new("#{Rails.root}/spec/support/wrong.png") expect(FactoryGirl.build(:pin, image: image)).to have(1).errors_on(:image_content_type) end
我希望我的两个例子都能成功运行。 但是,我的第二个例子失败了。 我没有得到wrong.png
content_type的任何错误。
我认为Paperclip的content_type
validation实际上会检查上传文件的文件格式(二进制数据编码)。 但似乎在这里,它只是检查文件扩展名。 此validation仅检查上传文件的扩展名吗?
我可能在这里遗漏了一些东西(配置?)。 Paperclip中是否还有其他validation可用于实现此目的? 或者在这种情况下我应该选择自定义validation器吗?
Paperclip于February 21, 2014
年February 21, 2014
发布的最新版本4.1.1
解决了此问题。
我的以下两个示例现在都正确传递。
it "Image is valid" do image = File.new("#{Rails.root}/spec/support/right.png") expect(FactoryGirl.build(:pin, image: image)).to be_valid end it "Image is invalid" do image = File.new("#{Rails.root}/spec/support/wrong.png") expect(FactoryGirl.build(:pin, image: image)).to have(1).errors_on(:image_content_type) end
经过一番研究发现,当我上传invalid image
,
例如:欺骗(重命名) wrong.txt
文件为wrong.png
并上传。
在Paperclip的先前版本中, wrong.png
通过带有飞行颜色的content_type
validation通过而不会出现任何错误,因为Paperclip
仅用于check the extensions
上载文件check the extensions
而不是内容。
然而,在当前版本的Paperclip 4.1.1
,同样的wrong.png
validation失败并在视图中抛出以下错误:
Image has an extension that does not match its contents
在调查服务器日志条目时,我发现了以下内容:
Command :: file -b –mime-type’/ var / folders / tg / 8sxl1vss4fb0sqtcrv3lzcfm0000gn / T / a7f21d0002b0d9d91eb158d702cd930320140317-531-swkmb8′[paperclip]内容类型欺骗:Filename wrong.png([“image / png”]),从文件命令发现的内容类型:text / plain。 请参阅文档以允许此组合。
在这里,您可以看到Paperclip实际上检查了上传文件的内容,说明了text/plain
,并且错误地说出了Content Type Spoof
。
希望我的发现能够帮助其他人了解Paperclip's content-type
validation是如何随着时间的推移而改进的。
- 使用FactoryGirl时,Paperclip :: Attachment作为字符串传递
- Paperclip – 从Amazon S3删除文件?
- `fetch’:找不到键:“S3_BUCKET_NAME”(KeyError)with paperclip / aws s3 / rails
- 如何使用带有导轨的回形针以及它在部署中如何工作?
- Ruby on Rails,Paperclip,Heroku,GitHub和AWS – 保护密钥
- 在我的ftp服务器上使用paperclip上传照片时出现随机错误
- rails paperclip没有通过sql查询从另一个模型直接访问
- 无法弄清楚是什么导致我的测试失败
- Ruby on Rails,Paperclip,亚马逊AWS S3和Heroku