How do I test a file upload in rails?

后端 未结 7 511
轻奢々
轻奢々 2020-12-07 09:29

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 fil

7条回答
  •  爱一瞬间的悲伤
    2020-12-07 10:20

    Mori's answer is correct, except that in Rails 3 instead of "ActionController::TestUploadedFile.new" you have to use "Rack::Test::UploadedFile.new".

    The file object that is created can then be used as a parameter value in Rspec or TestUnit tests.

    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
    

提交回复
热议问题