ActionDispatch :: Http :: UploadedFile在集成测试期间作为字符串传递

时间:2016-05-29 19:55:57

标签: ruby-on-rails ruby-on-rails-4 carrierwave minitest

我有一个相册模型和一个子图片模型,其中文件上传由carrierwave处理。

应用程序按预期运行,但是当我尝试为上传编写集成测试时失败。

从开发日志中,工作参数显示如下:

#include <iostream> #include <string> int main() { std::string str1 = "Hello "; int i = 2; std::string str2 = " World!"; std::string output = ""; output.append(str1).append(std::to_string(i)).append(str2); std::cout << output << std::endl; return 0; }

在集成测试期间,我获取如下参数:

Parameters: ..., "images"=>[#<ActionDispatch::Http::UploadedFile:0x007f8a42be2c78>...

正如您所看到的,在测试场景中,Parameters: ..., "images"=>["#<ActionDispatch::Http::UploadedFile:0x00000004706fd0>"...作为字符串传递(使用byebug确认),这导致测试失败。

如何让测试将此作为对象传递?

整合测试

#<ActionDispatch::Http::UploadedFile

来自test_helper.rb

require 'test_helper'
class AlbumsCreationTest < ActionDispatch::IntegrationTest

  def setup
    @user  = users(:archer)
    @file ||= File.open(File.expand_path(Rails.root + 'test/fixtures/cat1.jpg', __FILE__))
    @testfile  ||= uploaded_file_object(PicturesUploader, :image, @file)
  end

  test "should create new album with valid info" do
    log_in_as(@user)
    assert_difference 'Album.count', 1 do #This assertion fails
      post user_albums_path(@user), album: { title:       'test',
                                             description: 'test',
      }, images: [@testfile]
    end
    assert_redirected_to @user
  end
end

模型

# Upload File (Carrierwave) Ref: http://nicholshayes.co.uk/blog/?p=405
def uploaded_file_object(klass, attribute, file, content_type = 'image/jpeg')

filename = File.basename(file.path)
klass_label = klass.to_s.underscore

ActionDispatch::Http::UploadedFile.new(
  tempfile: file,
  filename: filename,
  head: %Q{Content-Disposition: form-data; name="#{klass_label}[#{attribute}]"; filename="#{filename}"},
  type: content_type
)
end

控制器

class Album < ActiveRecord::Base
  belongs_to :user
  has_many :pictures, dependent: :destroy
  accepts_nested_attributes_for :pictures, allow_destroy: true

  validates_presence_of :pictures
end

class Picture < ActiveRecord::Base
  belongs_to :album
  mount_uploader :image, PicturesUploader

  validates_integrity_of  :image
  validates_processing_of :image
  validates :image, presence: true,
                    file_size: { less_than: 10.megabytes }
end

1 个答案:

答案 0 :(得分:1)

<强>解决:

似乎uploaded_file_object方法在集成测试级别不起作用。

我回到使用fixture_file_upload,一切都按预期工作。