1

to_csvメソッドとimportメソッドを持つモデルがあります。これをrspecでテストして、正しい動作をすることを確認しようとしていますが、問題があります。次のエラーが発生します。

Failures:

  1) Category Class import should create a new record if id does not exist
     Failure/Error: Category.import("filename", product)
     NoMethodError:
       undefined method `path' for "filename":String

モデル:

class Category
  ...<snip>

  def self.import(file, product)
    product = Product.find(product)
    CSV.foreach(file.path, headers: true, col_sep: ";") do |row|
      row = row.to_hash
      row["variations"] = row["variations"].split(",").map { |s| s.strip }
      category = product.categories.find(row["id"]) || Category.new(row)
      if category.new_record?
        product.categories << category
      else
        category.update_attributes(row)
      end
    end
  end

  def self.to_csv(product, options = {})
    product = Product.find(product)
    CSV.generate(col_sep: ";") do |csv|
      csv << ['id','title','description','variations']
      product.categories.each do |category|
        variations = category.variations.join(',')
        csv << [category.id, category.title, category.description, variations]
      end
    end
  end
end

私のテスト:

describe Category do

  describe 'Class' do
    subject { Category }

    it { should respond_to(:import) }
    it { should respond_to(:to_csv) }

    let(:data) { "id;title;description;variations\r1;a title;;abd" }

    describe 'import' do
      it "should create a new record if id does not exist" do
        product = create(:product)
        File.stub(:open).with("filename","rb") { StringIO.new(data) }
        Category.import("filename", product)
      end
    end
  end
end
4

1 に答える 1

3

Category.importファイル名を取得するだけです:

Category.import("filename", product)

次にCategory.import、このファイル名をCSV.foreach呼び出しに渡します。

CSV.foreach(filename, headers: true, col_sep: ";") do |row|

その場合、スタブFile.openやそのジャズは必要ありません。

于 2013-03-02T15:13:25.270 に答える