生成假CSV以使用rspec进行测试

时间:2016-07-16 11:46:24

标签: csv ruby-on-rails-4 testing rspec

我想测试导入CSV文件的方法。 但我不知道如何生成虚假的CSV文件来测试它。 我尝试了很多我已经在堆栈上找到的解决方案,但它在我的情况下不起作用。

这是csv原始文件:

firstname,lastname,home_phone_number,mobile_phone_number,email,address
orsay,dup,0154862548,0658965848,orsay.dup@gmail.com,2 rue du pré paris
richard,planc,0145878596,0625147895,richard.planc@gmail.com,45 avenue du general leclerc

person.rb

 def self.import_data(file)
   filename = File.join Rails.root, file

   CSV.foreach(filename, headers: true, col_sep: ',') do  |row|
     firstname, lastname, home_phone_number, mobile_phone_number, email, address = row

     person = Person.find_or_create_by(firstname: row["firstname"], lastname: row['lastname'], address: row['address'] )
     if person.is_former_email?(row['email']) != true
       person.update_attributes({firstname: row['firstname'], lastname: row['lastname'], home_phone_number: row['home_phone_number'], mobile_phone_number: row['mobile_phone_number'], address: row['address'], email: row['email']})
    end
  end
end

person_spec.rb:

require "rails_helper"

RSpec.describe Person, :type => :model do


  describe "CSV file is valid" do
   file = #fake file
   it "should read in the csv" do
   end

   it "should have result" do
  end
 end

 describe "import valid data" do
  valid_data_file = #fake file
  it "save new people" do
   Person.delete_all
   expect { Person.import_data(valid_data_file)}.to change{ Person.count }.by(2)
   expect(Person.find_by(lastname: 'dup').email).to eq "orsay.dup@gmail.com"
 end

 it "update with new email" do
 end
end

describe "import invalid data" do
 invalid_data_file = #fake file
 it "should not update with former email" do
 end
 it "should not import twice from CSV" do
 end
 end
end

2 个答案:

答案 0 :(得分:0)

我成功使用Faked CSV Gem中的https://github.com/jiananlu/faked_csv来实现您使用虚假数据生成CSV文件的目的。

请按照以下步骤使用它:

  1. 打开命令行(即在OSX上打开Spotlight with CMD + Space,然后输入" Terminal")
  2. 通过运行命令gem install faked_csv安装Faked CSV Gem。注意:如果使用Ruby on Rails项目将gem 'faked_csv'添加到Gemfile,然后运行bundle install
  3. 通过键入Bash Terminal faked_csv --version
  4. 验证是否已成功安装伪造的CSV Gem
  5. 为伪造的CSV Gem创建配置文件,并在其中定义如何生成虚假数据。例如,下面将生成一个包含200行的CSV文件(或编辑为您希望的任意数量),并为每个字段包含逗号分隔的列。如果字段type的值以faker:为前缀,则请参阅" Usage"例如Faker Gem https://github.com/stympy/faker的部分。
  6. <强> my_faked_config.csv.json

    {
      "rows": 200,
      "fields": [
        {
          "name": "firstname",
          "type": "faker:name:first_name",
          "inject": ["luke", "dup", "planc"]
        },
        {
          "name": "lastname",
          "type": "faker:name:last_name",
          "inject": ["schoen", "orsay", "richard"]
        },
        {
          "name": "home_phone_number",
          "type": "rand:int",
          "range": [1000000000, 9999999999]
        },
        {
          "name": "mobile_phone_number",
          "type": "rand:int",
          "range": [1000000000, 9999999999]
        },
        {
          "name": "email",
          "type": "faker:internet:email"
        },
        {
          "name": "address",
          "type": "faker:address:street_address",
          "rotate": 200
        }
      ]
    }
    
    1. 运行以下命令以使用配置文件my_faked_config.csv.json在名为 my_faked_data.csv 的当前文件夹中生成CSV文件,其中包含虚假数据faked_csv -i my_faked_config.csv.json -o my_faked_data.csv
    2. 由于生成的文件在生成后可能不包含每列的关联标签,只需在 my_faked_data.csv firstname,lastname,home_phone_number,mobile_phone_number,email,address
    3. 的顶部手动插入以下行。
    4. 查看包含假数据的 my_faked_data.csv CSV文件的最终内容,该文件应与以下内容类似:
    5. <强> my_faked_data.csv

      firstname,lastname,home_phone_number,mobile_phone_number,email,address
      Kyler,Eichmann,8120675609,7804878030,norene@bergnaum.io,56006 Fadel Mission
      Hanna,Barton,9424088332,8720530995,anabel@moengoyette.name,874 Leannon Ways
      Mortimer,Stokes,5645028548,9662617821,moses@kihnlegros.org,566 Wilderman Falls
      Camden,Langworth,2622619338,1951547890,vincenza@gaylordkemmer.info,823 Esmeralda Pike
      Nikolas,Hessel,5476149226,1051193757,jonathon@ziemannnitzsche.name,276 Reinger Parks
      ...
      
      1. 使用下面显示的技术修改 person_spec.rb 单元测试,该技术将模拟数据传递给您 person.rb import_data函数的测试功能>文件
      2. <强> person_spec.rb

        require 'rails_helper'
        
        RSpec.describe Person, type: :model do
        
          describe 'Class' do
            subject { Person }
        
            it { should respond_to(:import_data) }
        
            let(:data) { "firstname,lastname,home_phone_number,mobile_phone_number,email,address\r1,Kyler,Eichmann,8120675609,7804878030,norene@bergnaum.io,56006 Fadel Mission" }
        
            describe "#import_data" do
              it "save new people" do
                File.stub(:open).with("filename", {:universal_newline=>false, :headers=>true}) {
                  StringIO.new(data)
                }
                Product.import("filename")
                expect(Product.find_by(firstname: 'Kyler').mobile_phone_number).to eq 7804878030
              end
            end
          end
        
        end
        

        注意:我自己使用它为我的Ruby on Rails CSV app生成一个包含有意义假数据的大型CSV文件。我的应用程序允许用户上传包含特定列名的CSV文件并将其保存到PostgreSQL数据库,然后在Paginated表视图中显示数据,并能够使用AJAX进行搜索和排序。

答案 1 :(得分:-1)

使用openoffice或excel并将文件另存为保存选项中的.csv文件。电子表格程序。