【发布时间】:2013-09-17 02:58:13
【问题描述】:
我正在使用 rspec 测试 CSV 上传器,并且我已经在 /spec/fixtures 中保存了一个测试文件,我使用 fixture_file_upload 将其拉入我的测试中:
let(:file) do
fixture_file_upload(
Rails.root.join("spec/fixtures/chargeback_test.csv"),
"text/csv"
)
end
这可行,但我在每个规范中都有文件路径。我想把我的代码放在工厂里来干掉我的代码,但我无法让 FactoryGirl 明白我想要从 FactoryGirl.create(:chargeback_csv) 返回一个 Tempfile。
我猜工厂应该是这样的:
include ActionDispatch::TestProcess
FactoryGirl.define do
factory :chargeback_csv, :class => "Tempfile" do
ignore do
path { Rails.root.join("spec/fixtures/chargeback_test.csv") }
mime_type { "text/csv" }
binary { false }
end
initialize_with { fixture_file_upload(path, mime_type, binary) }
end
end
但是,在我的规范中使用它会导致以下错误:
Failure/Error: let(:file) { FactoryGirl.create(:chargeback_csv) }
NoMethodError:
undefined method `save!' for #<Tempfile:0x112fec730>
解决了! save! 错误是因为 FactoryGirl 在它创建的新对象上调用 to_create 引起的。较新版本的 FactoryGirl 有一个选项 skip_create 来避免此错误。我使用的是旧版本,所以我在工厂中添加了to_create {},我的所有测试都再次变为绿色。
include ActionDispatch::TestProcess
FactoryGirl.define do
factory :chargeback_csv, :class => "Tempfile" do
to_create {}
ignore do
path { Rails.root.join("spec/fixtures/chargeback_test.csv") }
mime_type { "text/csv" }
binary { false }
end
initialize_with { fixture_file_upload(path, mime_type, binary) }
end
end
【问题讨论】:
标签: rspec factory-bot fixture