【问题标题】:Rspec to upload file with paramsRspec使用参数上传文件
【发布时间】:2018-04-18 01:03:13
【问题描述】:

我正在尝试编写用于测试上传功能的规范,并且代码实现按预期工作,但是当我尝试编写规范时,我无法弄清楚为什么在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 的调试器输出是什么?
  • @TomAranda:它在 .read 期间失败,如果我只用 params[:file] 通过,我仍然会得到同样的错误。所以我不确定是否必须将其格式化为 Action::Dispatcher 对象?如果是的话怎么办。
  • 不要拯救 StandardError - 只拯救你知道如何处理的错误。这将使调试几乎不可能,因为它会吞下大量异常。

标签: ruby-on-rails json ruby rspec actiondispatch


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    相关资源
    最近更新 更多