1

我正在尝试编写用于测试上传功能的规范,并且代码实现按预期工作,但是当我尝试编写规范时,我无法弄清楚为什么数据对话在JSON.parse. [导轨 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.parse失败并在失败之​​前获取值。convert_hashes_to_parameters(key, value)converted"[{"name":"Bob","key":"201","active":true}]"

我错过了什么?

4

1 回答 1

0

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
于 2017-11-08T21:33:34.220 回答