新手问题 [求助] 文件上传的测试代码怎么写

chq · 2014年08月16日 · 最后由 lokyoung 回复于 2015年12月08日 · 3999 次阅读

在测试 Controller 的 create 方法时,需要对表单中的文件上传进行测试,模型和视图如下:

class Picture < ActiveRecord::Base
  mount_uploader :image, PictureUploader #carrierwave上传
  validates :image, presence: true
end
<%= form_for @picture, html: {multipart: true} do |f| %>
  <%= f.label :image %>
  <%= f.file_field :image %>
<% end %>

测试代码如下

class PicturesControllerTest < ActionController::TestCase
  #...
  test "should create picture" do
    post :create, picture: { image: xxx } #怎样写这部分的测试代码
    assert_redirected_to picture_path(assigns(:picture))
  end
end

如题,怎样写文件上传的测试代码,或者思路 (http 协议/carrierwave 上传),进行测试呢?

image 的值,是个文件对象可以吗?比如 File. open xxx

最近在读 @andor_chen 翻译的 Everyday Rails Testing with Rspec, 第十章介绍了如何测试文件上传,如果你是要 Rspec,你可以选择在 spec/factories文件夹中放一个小文件,然后可以在FactoryGirl的预构件中引用,

FactoryGirl.define do
  factory :picture do
    image {File.new("#{Rails.root}/spec/factories/avatar.png")}
  end
end

在控制器测试里可以直接用

it "upload image" do
  post :create, picture: create(:picture)
  expect(response).to redirect_to picture_path(assigns(:picture))
end

如果使用默认的 MiniTest 你可以使用 Rails helper fixture_file_upload(filename, mime_type)

post :create, picture: fixture_file_upload('/test/data/logo.png', 'image/png')
image = Rack::Test::UploadedFile.new(xxx_path)
post :create, picture: { image: xxx }

感谢 @dotcomXY 引荐这本书,补上电子书的购买链接 https://selfstore.io/products/3

3q 4 @dotcomXY 's code

post :create, picture: fixture_file_upload('/test/data/logo.png', 'image/png')

and the @dotcomXY's book

#4 楼 @andor_chen 买过并看过,中文的看着舒服,感谢翻译。不过已经改用 minitest 了~

#6 楼 @loveltyoic 想请教一下,在 minitest 中测试上传功能,上传的文件会和原本的文件在同一个文件夹里。这个有办法解决么。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号