dailammoc
dailammoc

Reputation: 144

Writing rspec test for CSV upload file

I have the code that implement csv upload like this:

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

so how do I write rspec test for this?

Upvotes: 1

Views: 4147

Answers (2)

Semih Arslanoglu
Semih Arslanoglu

Reputation: 1139

If any one needed model tests for 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

Upvotes: 2

Aaron K
Aaron K

Reputation: 6961

There are lots of ways to write controller specs. There are many good resources online outlining how to write them in different styles. I suggest starting with the RSpec docs on controller specs:

In general they go something like:

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

Upvotes: 3

Related Questions