我有一个模型,它有一个 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