简体   繁体   中英

Undefined Method when running rspec test using a stub

I have a model which has a to_csv method and import method, trying to test this in rspec to make sure it does the right thing but having a problem. I get the following error:

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

Model:

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

My Test:

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

I would just make Category.import take a filename:

Category.import("filename", product)

Then Category.import just passes this filename to the CSV.foreach call:

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

It's then not necessary to stub File.open or any of that jazz.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM