fixture_file_upload有{file}不存在错误

han*_*hee 17 rspec ruby-on-rails

以下是我上传文件的测试代码.

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
Run Code Online (Sandbox Code Playgroud)

但是,当我运行rspec规范时,它会产生下面的错误

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)>'
Run Code Online (Sandbox Code Playgroud)

我搜索了很多地方,但我仍然无法找出背后的原因.任何的想法?

小智 26

Fixture_file_upload基本上仍然有效.您只需要确保spec_helper.rb文件中的灯具路径已取消注释并正确设置为spec/fixtures路径并包括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"

  ...
Run Code Online (Sandbox Code Playgroud)

如果要在测试中指定文件,请确保在文件名前加上"/",如下例所示:

describe "POST /subscriber_imports" do
  let(:file) { { :file => fixture_file_upload('/files/data.csv', 'text/csv') } }
  subject { post :create, :subscriber_import => file }
  ...
end
Run Code Online (Sandbox Code Playgroud)

文件的绝对路径是指定的基本路径config.fixture_path加上fixture_file_upload函数调用中指定的相对路径.所以,在这个例子中,file.csv必须放入#{::Rails.root}/spec/fixtures/files/data.csv

  • 还要注意`include ActionDispatch :: TestProcess`.这特别为我解决了这个问题 (3认同)

thi*_*ign 5

这就是我的做法Rails 6RSpec并且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
Run Code Online (Sandbox Code Playgroud)

ActionDispatch::TestProcess除非您确定所包含的内容,否则请勿包含或任何其他代码。


hec*_*rsq 1

根据问题投票最多的答案,您必须将该文件放在 {Rails.root}/spec/fixtures/files 下