为CSV上传文件编写rspec测试

时间:2014-04-17 03:48:49

标签: csv rspec

我有像这样实现csv上传的代码:

def Hotel.import(file)
  CSV.foreach(file.path, headers: true) do |row|
    product = find_by_id(row["id"]) || new
    product.attributes = row.to_hash
    product.save
  end
end

def import
  Hotel.import(params[:file])
  redirect_to root_url, notice: "Product was successfully Imported."
end

那么如何为此编写rspec测试?

2 个答案:

答案 0 :(得分:2)

有很多方法可以编写控制器规格。网上有很多很好的资源,概述了如何以不同的风格编写它们。我建议从控制器规范的RSpec文档开始:

一般来说,它们会像:

require "spec_helper"

describe ProductsController do
  describe "POST #import" do
    it "redirects to the home page" do
      allow(Hotel).to receive(:import).with("foo.txt")
      post :import, file: "foo.txt"
      expect(response).to redirect_to root_url
    end

    it "adds a flash notice" do
      allow(Hotel).to receive(:import).with("foo.txt")
      post :import, file: "foo.txt"
      expect(flash[:notice]).to eq "Product was successfully imported."
    end

    it "imports the hotel file" do
      expect(Hotel).to receive(:import).with("foo.txt")
      post :import, file: "foo.txt"
    end
  end
end

答案 1 :(得分:0)

如果需要对rspec进行模型测试。

require 'rails_helper'

RSpec.describe Product, type: :model do
  describe 'import' do
    before :each do
      @file = fixture_file_upload('data.csv', 'csv')
    end

    context 'when file is provided' do
      it 'imports products' do
        Product.import(@file)
        expect(Product.find_by(part_number: '0121G00047P').description)
          .to eq 'GALV x FAB x .026 x 29.88 x 17.56'
      end
    end
  end
end