如何在rails中测试文件上传?

ani*_*mal 99 ruby testing upload ruby-on-rails

我有一个控制器,负责接受JSON文件,然后处理JSON文件,为我们的应用程序做一些用户维护.在用户测试文件上传和处理工作,但当然我想在我们的测试中自动化测试用户维护的过程.如何在功能测试框架中将文件上传到控制器?

ani*_*mal 110

搜索了这个问题并且无法找到它,或者它在Stack Overflow上的答案,但在其他地方找到它,所以我要求在SO上提供它.

rails框架具有一个功能fixture_file_upload(Rails 2 Rails 3,Rails 5),它将在您的fixtures目录中搜索指定的文件,并使其在功能测试中作为控制器的测试文件.要使用它:

1)将您要上传的文件放在fixtures/files子目录中的测试中进行测试.

2)在单元测试中,您可以通过调用fixture_file_upload('path','mime-type')来获取测试文件.

例如:

bulk_json = fixture_file_upload('files/bulk_bookmark.json','application/json')

3)调用post方法来命中你想要的控制器动作,传递fixture_file_upload返回的对象作为上传的参数.

例如:

post :bookmark, :bulkfile => bulk_json

或者在Rails 5中: post :bookmark, params: {bulkfile: bulk_json}

这将使用fixtures目录中文件的Tempfile副本运行模拟后期处理,然后返回到单元测试,以便您可以开始检查帖子的结果.

  • 这在rails 3上不起作用.似乎action_controller/test_process文件在activesupport 3中不可用.我在这里打开了一个新问题 - http://stackoverflow.com/questions/3966263/attachment-fu-testing-in-rails-3 (2认同)

小智 84

Mori的答案是正确的,除了在Rails 3而不是"ActionController :: TestUploadedFile.new"中你必须使用"Rack :: Test :: UploadedFile.new".

然后,可以将创建的文件对象用作Rspec或TestUnit测试中的参数值.

test "image upload" do
  test_image = path-to-fixtures-image + "/Test.jpg"
  file = Rack::Test::UploadedFile.new(test_image, "image/jpeg")
  post "/create", :user => { :avatar => file }
  # assert desired results
  post "/create", :user => { :avatar => file }     

  assert_response 201
  assert_response :success
end
Run Code Online (Sandbox Code Playgroud)

  • 这也与Rails 4完美配合.谢谢! (2认同)

Dav*_*les 23

我认为最好以这种方式使用新的ActionDispatch :: Http :: UploadedFile:

uploaded_file = ActionDispatch::Http::UploadedFile.new({
    :tempfile => File.new(Rails.root.join("test/fixtures/files/test.jpg"))
})
assert model.valid?
Run Code Online (Sandbox Code Playgroud)

这样,您可以使用在验证中使用的相同方法(例如tempfile).


Mor*_*ori 8

来自The Rspec Book,B13.0:

Rails'提供了一个ActionController :: TestUploadedFile类,可用于表示控制器规范的params哈希中的上传文件,如下所示:

describe UsersController, "POST create" do
  after do
    # if files are stored on the file system
    # be sure to clean them up
  end

  it "should be able to upload a user's avatar image" do
    image = fixture_path + "/test_avatar.png"
    file = ActionController::TestUploadedFile.new image, "image/png"
    post :create, :user => { :avatar => file }
    User.last.avatar.original_filename.should == "test_avatar.png"
  end
end
Run Code Online (Sandbox Code Playgroud)

此规范要求您在spec/fixtures目录中有一个test_avatar.png图像.它需要该文件,将其上传到控制器,控制器将创建并保存真实的用户模型.

  • 当我使用此代码运行测试时,我收到"未初始化的常量ActionController :: TestUploadedFile"错误.我还需要在文件中要求的其他内容吗? (2认同)