Rspec 上传带参数的文件

Rspec to upload file with params

我正在尝试编写用于测试上传功能的规范并且代码实现按预期工作但是当我尝试编写规范时我无法弄清楚为什么数据对话在 JSON.parse 期间失败. [ Rails 5.X ]

方法

def upload
  #some validation
  begin
    puts params[:file]
    json = JSON.parse(params[:file].read)
    #rest of the validation
  rescue StandardError, JSON::ParserError, HttpServices::BadHttpResponseError
      flash[:style] = :error
  end
end

规格:

describe "upload" do
  before do
    read = file_fixture("empy_details.json").read
    @file = Hash.new
    @file['emp'] = read #debugger > @file:{emp: [{"name":"Bob","key":"201","active":true}]}
  end

  it 'should upload' do
    post :upload, params: { :file => @file }, as: :json
    expect(flash[:style]).to eq(:success)
  end
end

方法puts params[:file]打印

{"emp"=>"[{\"name\":\"Bob\",\"key\":\"201\",\"active\":true}]\n"} 

JSON.parseconvert_hashes_to_parameters(key, value) 方法处失败 converted 在失败前获取 "[{"name":"Bob","key":"201","active":true}]" 的值。

我错过了什么?

params[:file].read 在通过 Rspec 传递文件时抛出异常,我更改了控制器方法代码以适应 params[:file]

def upload
  #some validation
  begin
    puts params[:file]
    if params[:file].respond_to?(:read)
      json = JSON.parse(params[:file].read)
    else
      json = JSON.parse(params[:file])
    end
    #rest of the validation
  rescue StandardError, JSON::ParserError, HttpServices::BadHttpResponseError
      flash[:style] = :error
  end
end