You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 21:07:06