使用存根运行rspec测试时的未定义方法

时间:2013-03-02 15:12:00

标签: ruby-on-rails rspec rspec-rails

我有一个模型,它有一个to_csv方法和导入方法,试图在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

1 个答案:

答案 0 :(得分:3)

我只想让Category.import取一个文件名:

Category.import("filename", product)

然后Category.import只是将此文件名传递给CSV.foreach来电:

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

然后没有必要存根File.open或任何爵士乐。

相关问题