【问题标题】:fixture_file_upload has {file} does not exist errorfixture_file_upload 有 {file} 不存在错误
【发布时间】:2012-02-19 03:37:55
【问题描述】:

下面是我上传文件的测试代码。

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)>'

我用谷歌搜索了很多地方,但我仍然无法找出背后的原因。有什么想法吗?

【问题讨论】:

标签: ruby-on-rails rspec


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    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"
    
      ...
    

    如果您在测试中指定文件,请务必在文件名前加上“/”,如下例所示:

    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

    【讨论】:

    • 还要注意include ActionDispatch::TestProcess。这特别为我解决了这个问题
    • include ActionDispatch::TestProcess 也为我解决了这个问题。奇怪的是,我们在其他 rspec 测试中使用了 fixture_file_upload 很好,但新的测试失败了。可能是这个新规范被限定在一个模块中。
    【解决方案3】:

    这就是我使用Rails 6RSpecRack::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 或任何其他代码,除非您确定您所包含的内容。

    【讨论】:

    • fixture_file_upload 是 Rack::Test::UploadedFile.new(File.join(ActionDispatch::IntegrationTest.file_fixture_path, path), type) 的快捷方式
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    • 2013-11-04
    • 2021-05-30
    • 1970-01-01
    • 2013-08-25
    相关资源
    最近更新 更多