下面的代码在Rails 4.2应用程序中测试模型规范中的图像验证,该应用程序带有RSpec 3.5,神龛宝石用于文件上传。
我的问题是:
文件上传设置的其他方面在控制器和特性规范中进行了测试,这与这个问题无关。
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发布于 2017-07-01 23:15:29
我建议您分别测试元数据提取和验证。您需要在实际的IOs中测试的元数据提取,但是对于验证测试,您可以使用所需的元数据分配缓存的文件,而这些元数据并不一定实际存在。
RSpec.describe ImageUploader do
def uploaded_file(metadata = {})
Shrine.uploaded_file(
"id" => "123",
"storage" => "cache",
"metadata" => {"mime_type" => "image/jpeg", "size" => 100}.merge(metadata)
)
end
let(:share_image) do
FactoryGirl.build(:share_image, image: uploaded_file(metadata).to_json)
end
let(:metadata) { Hash.new }
describe "validations" do
before(:each) { share_image.valid? }
context "when image is correct" do
it "passes" do
expect(share_image.errors).to be_empty
end
end
context "when extension is correct but MIME types isn't" do
let(:metadata) { Hash["filename" => "image.jpg", mime_type => "text/plain"] }
it "fails" do
expect(share_image.errors[:image].to_s).to include("isn't of allowed type")
end
end
context "when file is larger than 10MB" do
let(:metadata) { Hash["size" => 11 * 1024 * 1024] }
it "fails" do
expect(share_image.errors[:image].to_s).to include("too large")
end
end
end
end发布于 2017-06-28 21:24:44
与其通过Rack::Test::UploadedFile路由上传,不如直接使用夹具或工厂或直接在测试中创建附件元数据记录。最终的结果应该是您有附件元数据(这是您上传文件时构造的),它引用您的文件,而不必通过上传代码运行它。我不确定用神殿做这件事的具体细节,但是这种技术在像Paperclip这样的库中很好地工作。在神殿中,这将意味着直接构建一个引用您的文件的Shrine::UploadedFile记录。
https://stackoverflow.com/questions/44812403
复制相似问题