Ruby on rails 夹具文件上传有{file}不存在错误

Ruby on rails 夹具文件上传有{file}不存在错误,ruby-on-rails,rspec,Ruby On Rails,Rspec,下面是我上传文件的测试代码 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

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

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)>'
失败/错误:@file=fixture\u file\u upload('test.csv','text/csv'))
运行时错误:
test.csv文件不存在
#./spec/controllers/quote_controller_spec.rb:29:in'block(3层)in'

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

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

Fixture\u file\u上传基本上仍然有效。您只需确保
spec\u helper.rb
文件中的fixtures路径未注释并正确设置为
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\u path
中指定的基本路径加上
fixture\u file\u upload
函数调用中指定的相对路径。因此,在本例中,
file.csv
必须放在
{::Rails.root}/spec/fixtures/files/data.csv
这就是我如何使用
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

或任何其他代码,除非您确定所包含的内容。

从SO中找到了一个解决方案。显然,我必须用这行代码替换fixture\u file\u upload,即Rails.root.join('spec/fixtures/Test.csv'),'text/csv')fixture\u file\u upload不适用于Rails 3.1?我在升级到3.2之后开始看到这一点,Rails 3.2中似乎出现了问题,在github上检查这个问题:还要注意
包含ActionDispatch::TestProcess
。这特别解决了我的问题
include ActionDispatch::TestProcess
也解决了我的问题。奇怪的是,我们在其他rspec测试中使用了
fixture\u file\u upload
fine,但在新的测试中失败了。可能是这个新规范的作用域在一个模块中。