只设置一次假数据

时间:2013-09-24 16:10:31

标签: ruby-on-rails ruby controller state-management faker

我正在开发没有型号的rails应用程序。我在lib中有一个类FakeMaker,它构建了一堆用于显示目的的虚假实体。

我想测试删除功能,但问题是我每次点击控制器时都会重新初始化我的假数据集。

我只想运行一次数据测试创建器,以便我只有一组假数据。

我尝试使用||=before_filterFakeMaker中的类方法,会话存储但是每次控制器被命中时都会出现重新初始化数据集的问题。< / p>

控制器代码:

class HomeController < ApplicationController
  include FakeMaker

  before_filter :set_up_fake_data

  def index
    @workstations = @data[:workstations]
    @data_sources = @data[:data_sources]
  end

  private

  def set_fake_data
    @data ||= session[:fake_data]
  end

  def initialize_data
    session[:fake_data] = set_up_fake_data
  end
end  

lib中的FakeMaker:

module FakeMaker
  include ActionView::Helpers::NumberHelper

  SOURCE_CIDNE = "CIDNE"
  SOURCE_DCGS = "DCGS"
  TYPES_CIDNE = Faker::Lorem.words(num = 10)
  TYPES_DCGS = Faker::Lorem.words(num = 4)

  def set_up_fake_data
    @data ||= { workstations: fake_maker("workstation", 8), data_sources: fake_maker("data_source", 2) }
  end

  def fake_maker(type, count)
    fake = []
    case type
    when "report"
      count.times { fake << fake_report }
    when "workstation"
      count.times { fake << fake_workstation }
    when "data_source"
      fake = fake_data_source
    end
    fake
  end

  def fake_report
    report = { source: [SOURCE_CIDNE, SOURCE_DCGS].sample,
               count: number_with_delimiter(Faker::Number.number(5), :delimiter => ',') }
    report[:type] = report[:source] == SOURCE_CIDNE ? TYPES_CIDNE.sample : TYPES_DCGS.sample.capitalize
    report
  end

  def fake_workstation
    { name: Faker::Lorem.word,
      downloaded: number_with_delimiter(Faker::Number.number(3), :delimiter => ','),
      available: number_with_delimiter(Faker::Number.number(5), :delimiter => ','),
      last_connect: fake_time,
      queueJSON: fake_queueJSON,
      historyJSON: fake_historyJSON }
  end

  def fake_data_source
    data_sources = []
    ["CIDNE", "DCGS"].each do |source|
      data_sources << { type: source,
                        name: Faker::Internet.url,
                        status: ["UP", "DOWN"].sample }
    end
    data_sources
  end


  def fake_historyJSON
    history = []
    12.times { history << fake_history }
    history
  end

  def fake_queueJSON
    queue = []
    35.times { queue << fake_queue }
    queue
  end

  def fake_history
    { sentTimestamp: fake_time,
      reportID: Faker::Number.number(5)}
  end

  def fake_queue
    { priority: Faker::Number.number(3),
      queuedTimestamp: fake_time,
      reportID: Faker::Number.number(5)}
  end

  def fake_time
    Random.rand(10.weeks).ago.strftime("%Y-%m-%d %H:%M:%S")
  end


end

0 个答案:

没有答案