如何在 Rails 中测试文件上传? [英] How do I test a file upload in rails?

查看:35
本文介绍了如何在 Rails 中测试文件上传?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a controller which is responsible for accepting JSON files and then processing the JSON files to do some user maintenance for our application. In user testing the file upload and processing works, but of course I would like to automate the process of testing the user maintenance in our testing. How can I upload a file to a controller in the functional testing framework?

推荐答案

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

Searched for this question and could not find it, or its answer on Stack Overflow, but found it elsewhere, so I'm asking to make it available on SO.

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

The rails framework has a function fixture_file_upload (Rails 2 Rails 3, Rails 5), which will search your fixtures directory for the file specified and will make it available as a test file for the controller in functional testing. To use it:

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

1) Put your file to be uploaded in the test in your fixtures/files subdirectory for testing.

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

2) In your unit test you can get your testing file by calling fixture_file_upload('path','mime-type').

例如:

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

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

3) call the post method to hit the controller action you want, passing the object returned by fixture_file_upload as the parameter for the upload.

例如:

post :bookmark, :bulkfile =>bulk_json

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

Or in Rails 5: post :bookmark, params: {bulkfile: bulk_json}

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

This will run through the simulated post process using a Tempfile copy of the file in your fixtures directory and then return to your unit test so you can start examining the results of the post.

这篇关于如何在 Rails 中测试文件上传?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆