[英]Can't use a model using CarrierWave without a real file in Rails using rspec
I'm trying to run a test using a model, but I'm trying not to have to use a file for real here.我正在尝试使用模型运行测试,但我试图不必在这里使用真实的文件。
My use case is in rspec I try to create that object with a property handled by CarrierWave using FactoryBot, but I don't know what to pass to my icon
property except a real file.我的用例是在 rspec 中,我尝试使用由 CarrierWave 使用 FactoryBot 处理的属性创建该对象,但除了真实文件之外,我不知道将什么传递给我的icon
属性。
My model is like this:我的模型是这样的:
class MyItem < ApplicationRecord
validates :icon, presence: true
mount_uploader :icon, MyIconUploader
end
Using FactoryBot, when I try to run create
I have this error:使用 FactoryBot,当我尝试运行create
出现此错误:
ActiveRecord::RecordInvalid:
Validation failed: Icon can't be blank
Only thing that works seems to be the following:唯一有效的似乎是以下内容:
FactoryBot.define do
factory :item, class: 'MyItem' do
icon { Rack::Test::UploadedFile.new(File.join(Rails.root, 'spec', 'assets', 'images', 'image.jpg')) }
end
end
Giving it a file from memory would also work for me, as long as it is not a physical one.只要它不是物理文件,从内存中给它一个文件也适用于我。
You can use StringIO
class for that.您可以StringIO
使用StringIO
类。 Since CarrierWave also expects a filename on the given IO object, you would also need to subclass StringIO
to something like this:由于 CarrierWave 还需要给定 IO 对象上的文件名,因此您还需要将StringIO
子类StringIO
以下内容:
class StringIOWithName < StringIO
def initialize(stream, filename)
super(stream)
@original_filename = filename
end
attr_reader :original_filename
end
Then you can give an instance of StringIOWithName
to Carrierwave.然后你可以给StringIOWithName
一个StringIOWithName
的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.