【问题标题】:How to test that a file is uploaded in a controller?如何测试文件是否上传到控制器中?
【发布时间】:2015-03-04 23:15:42
【问题描述】:

我正在尝试在我上传图片时测试我的用户是否具有照片值。它在浏览器中运行良好,并且测试的基本功能通过了,但是如果我尝试断言 user.photo 不为零,它就会失败。这是测试

describe 'POST #update' do
  context 'when there is an image' do
    it 'renders the crop template' do
      login(user)
      photo = File.open(File.join(Rails.root, '/spec/fixtures/images/bob-weir.jpg'))
      post :update, user: { photo: photo }

      expect(response).to render_template('crop')
      user.reload
      expect(user.photo.file).to_not be_nil
    end
  end
end

正在生产:

Failure/Error: expect(user.photo.file).to_not be_nil
       expected: not nil
            got: nil

如果我在测试结束时放置一个调试器并执行 user.photo,我会得到:

(byebug) user.photo

#<PhotoUploader:0x007fa447029480 @model=#<User id: 226, ..... photo: nil>,
@mounted_as=:photo, @storage=#<CarrierWave::Storage::File:0x007fa4468ddbb8 
@uploader=#<PhotoUploader:0x007fa447029480 ...>>>

有什么方法可以确保控制器确实在数据库中保存了照片值?它只是模型上的一个属性,它将文件名保存为字符串。

【问题讨论】:

    标签: ruby-on-rails-4 rspec carrierwave factory-bot uploader


    【解决方案1】:

    答案是使用fixture_file_upload:http://api.rubyonrails.org/classes/ActionDispatch/TestProcess.html#method-i-fixture_file_upload

    post :update, user: { photo: fixture_file_upload('images/bob-weir.jpg', 'image/jpg') }
    

    另外,如果你想在工厂中使用它,它会是:

    Rack::Test::UploadedFile.new(File.open(File.join(Rails.root, '/spec/fixtures/images/bob-weir.jpg')))
    

    【讨论】:

      猜你喜欢
      • 2012-08-20
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 2012-04-15
      • 1970-01-01
      • 1970-01-01
      • 2013-02-27
      相关资源
      最近更新 更多