ruby-on-rails – 如何使用RSpec测试CSV导入?
发布时间:2020-12-17 03:29:32 所属栏目:百科 来源:网络整理
导读:我有使用存根的问题,不知道如何测试这个类方法: class Artist ActiveRecord::Base def self.import(file) CSV.foreach(file.path,headers: true) do |row| Artist.find_or_create_by(row.to_hash) end endendRSpec.describe Artist,type: :model do describ
我有使用存根的问题,不知道如何测试这个类方法:
class Artist < ActiveRecord::Base def self.import(file) CSV.foreach(file.path,headers: true) do |row| Artist.find_or_create_by(row.to_hash) end end end RSpec.describe Artist,type: :model do describe ".import" do before :each do create(:artist,name: 'artist1',facebook_url: nil) create(:artist,name: 'artist2',facebook_url: "facebook_url") end context "when facebook_url is empty" do it "updates facebook_url" do #Here I should somehow stub CSV with name,facebook_url #headers and row: artist1,artist1_facebook_url - HOW ? Artist.import(file) expect(Artist.find_by(name: 'artist1').facebook_url).to eq "artist1_facebook_url" end end end end 我该如何存根以使此测试工作? 解决方法
你可以这样写:
file = CSV.generate do |csv| csv << ["name","facebook_url"] #hash keys csv << ["artict1","nil"] csv << ["artict2","facebook_url"] end # String instead of file 然后这样的事情: expect(File).to receive(:open).with("filename","r").and_return(file) Artist.import("filename") expect(Artist.find_by(name: 'artist1').facebook_url).to eq "artist1_facebook_url" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |