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 回答