Rails中使用Factory Bot创建带附件的Disbursement工厂示例
解决FactoryBot中添加动态文件附件的问题
方法1:使用临时文件(通用方案)
直接在工厂里生成临时空文本文件,绑定到physical_copy字段:
FactoryBot.define do factory :disbursement do name { "Any" } date { Date.current } iban { "DE123456" } # 生成临时文件作为附件 physical_copy do file = Tempfile.new(["disbursement", ".txt"]) file.close # 关闭文件后才能被Active Storage读取 Rack::Test::UploadedFile.new(file.path, "text/plain") end end end
方法2:使用StringIO(无需生成实际文件)
用StringIO模拟文件对象,更轻量:
FactoryBot.define do factory :disbursement do name { "Any" } date { Date.current } iban { "DE123456" } physical_copy do io = StringIO.new("") io.class.class_eval { attr_accessor :original_filename, :content_type } io.original_filename = "disbursement.txt" io.content_type = "text/plain" io end end end
方法3:Active Storage简化写法(Rails 6+)
如果项目用了Active Storage,可直接用fixture_file_upload:
FactoryBot.define do factory :disbursement do name { "Any" } date { Date.current } iban { "DE123456" } physical_copy { fixture_file_upload(Rails.root.join('spec', 'fixtures', 'files', 'empty.txt'), 'text/plain') } end end
注:需提前在spec/fixtures/files目录下创建empty.txt空文件
配合Cucumber步骤使用
在Cucumber的Given步骤中调用工厂:
Given("there is a disbursement") do FactoryBot.create(:disbursement) end
之后就能通过Given there is a disbursement语句直接生成符合验证要求的disbursement实例,避免重复填写表单的冗余代码。
内容的提问来源于stack exchange,提问作者Julian
相关产品推荐
相关产品推荐

