gpt4 book ai didi

ruby-on-rails - 如何使用 RSpec 测试 CSV 导入?

转载 作者:行者123 更新时间:2023-12-04 03:35:38 25 4
gpt4 key购买 nike

我在使用 stub 时遇到问题,不知道我应该如何测试这个类方法:

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

我应该如何 stub 以使这个测试工作?

最佳答案

你可以这样写:

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"

关于ruby-on-rails - 如何使用 RSpec 测试 CSV 导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35340693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com