How do I test a file upload in rails?

后端 未结 7 521
轻奢々
轻奢々 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:14

    From The Rspec Book, B13.0:

    Rails’ provides an ActionController::TestUploadedFile class which can be used to represent an uploaded file in the params hash of a controller spec, like this:

    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
    

    This spec would require that you have a test_avatar.png image in the spec/fixtures directory. It would take that file, upload it to the controller, and the controller would create and save a real User model.

提交回复
热议问题