微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Rails 6 Minitest 文件上传

如何解决Rails 6 Minitest 文件上传

我正在尝试使用 Minitest 在 Rails 6 中创建文件上传测试。 我在 Stack Overflow 上看过几篇关于这个问题的帖子,但我仍然没有让它工作。 测试时手动上传工作正常。但我想对其进行测试。 我是测试新手!

我的路线

post "upload_validation",to: "products#upload_validation"

我的控制器

def upload_validation
    body = file_format_validation
    if body.present?
      request = RestClient.post(api_v1_products_url,body.to_json,set_http_headers({ content_type: :json,accept: :json }))

      json_response = JSON.parse(request.body)

      flash[:notice] = "Uploaded: #{json_response['products_uploaded']} | Saved: #{json_response['products_saved']}"
      redirect_to root_path
    else
      redirect_to root_path,alert: "Invalid file"
    end
  end

private

  def file_format_validation
    if params.key?(:file) && params[:file].content_type == "application/json"
      uploaded_file = params[:file]
      serialized_products = uploaded_file.tempfile.read
      JSON.parse(serialized_products)
    end
  end

  def set_http_headers(args = {})
    headers = {
      x_user_email: current_user.email,x_user_token: current_user.reload.authentication_token
    }
    if args.empty?
      headers
    else
      headers.merge(args)
    end
  end

我的观点

<%= form_with url: upload_validation_path,local: false,multipart: true do |form| %>
      <%= form.file_field :file,accept: 'application/json',required: true %>
      <%= submit_tag 'Uplaod',class: "btn btn-primary"%>
<% end %>

我的测试

在我的 test/system/products_test.rb 中,我有以下代码。但是当我运行测试时

class ProductsTest < ApplicationSystemTestCase   
  test "upload file" do

    file_path = "#{Rails.root}/test/fixtures/files/products-test.json"
    json_file = fixture_file_upload("#{Rails.root}/test/fixtures/files/products-test.json",'application/json')
    post upload_validation_path,params: { file: json_file },headers: {
      content_type: "application/json"
    }
    assert_response 201
  end
end

当我运行测试时,我得到

Error:
ProductsTest#test_upload_file:
DRb::DRbRemoteError: undefined method `post' for #<ProductsTest:0x00007f9b67ac99a0> (NoMethodError)
    test/system/products_test.rb:22:in `block in <class:ProductsTest>'

如果我使用 post upload_validation_url,我得到

Error:
ProductsTest#test_upload_file:
ArgumentError: Missing host to link to! Please provide the :host parameter,set default_url_options[:host],or set :only_path to true
    test/system/products_test.rb:22:in `block in <class:ProductsTest>'

我做错了什么?

谢谢

解决方法

ApplicationSystemTestCase 在这里似乎是错误的。

改用 ActionController::TestCase

class ProductsControllerTest < ActionController::TestCase 中名为 products_controller_test.rb 的文件中尝试 test/controllers/products_controller

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。