以下是我上传文件的测试代码。
describe "file process" do
before(:each) do
# debugger
@file = fixture_file_upload('test.csv', 'text/csv')
end
it "should be able to upload file" do
post :upload_csv, :upload => @file
response.should be_success
end
end
但是,当我运行 rspec spec 时,它会产生以下错误
Failure/Error: @file = fixture_file_upload('test.csv', 'text/csv')
RuntimeError:
test.csv file does not exist
# ./spec/controllers/quotation_controller_spec.rb:29:in `block (3 levels) in <top (required)>'
我搜索了很多地方,但我仍然无法找出背后的原因。有什么想法吗?
答案 0 :(得分:27)
Fixture_file_upload基本上仍然有效。您只需要确保spec_helper.rb
文件中的灯具路径已取消注释&amp;正确设置为spec/fixtures
路径&amp;包括ActionDispath::TestProcess
:
RSpec.configure do |config|
config.include ActionDispatch::TestProcess
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
...
如果要在测试中指定文件,请确保在文件名前加上“/”,如下例所示:
describe "POST /subscriber_imports" do
let(:file) { { :file => fixture_file_upload('/files/data.csv', 'text/csv') } }
subject { post :create, :subscriber_import => file }
...
end
文件的绝对路径是config.fixture_path
中指定的基本路径加上fixture_file_upload
函数调用中指定的相对路径。因此,在此示例中,file.csv
必须放在#{::Rails.root}/spec/fixtures/files/data.csv
答案 1 :(得分:0)
基于对this问题的最多投票答案,您必须将该文件放在{Rails.root} / spec / fixtures / files
下答案 2 :(得分:0)
这就是我使用Rails 6
,RSpec
和Rack::Test::UploadedFile
的方式
describe 'POST /create' do
it 'responds with success' do
post :create, params: {
company: {
logo: Rack::Test::UploadedFile.new("#{Rails.root}/spec/fixtures/test-pic.png"),
name: 'test'
}
}
expect(response).to be_successful
end
end
DO NOT include ActionDispatch::TestProcess
或任何其他代码,除非您确定要包含的内容。