繁体   English   中英

在Ruby on Rails中为rake任务和测试文件放置辅助函数的位置?

[英]Where to put helper functions for rake tasks and test files in Ruby on Rails?

在我的Rails应用程序中,我在/lib/tasks有一个文件sample_data.rb以及my /spec目录中的一堆测试文件。

所有这些文件通常共享通用功能,例如:

def random_address
  [Faker::Address.street_address, Faker::Address.city].join("\n")
end

我应该把这些辅助功能放在哪里? 对此有什么约定吗?

谢谢你的帮助!

您可以使用静态函数创建静态类。 这看起来像这样:

class HelperFunctions

     def self.random_address
          [Faker::Address.street_address, Faker::Address.city].join("\n")
     end

     def self.otherFunction
     end
end

然后,您需要做的就是:

  1. 在您要使用的文件中包含您的帮助程序类
  2. 执行它像:

     HelperFunctions::random_address(anyParametersYouMightHave) 

执行此操作时,请确保在HelperFunctions类中包含任何依赖项。

如果您确定它只是特定的rake,您也可以直接在RAILS_ROOT/Rakefile (对于您使用的示例可能不是这种情况)。

我用它来简化rake的invoke语法:

#!/usr/bin/env rake
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.

require File.expand_path('../config/application', __FILE__)

def invoke( task_name )
  Rake::Task[ task_name ].invoke
end

MyApp::Application.load_tasks

这样,我可以在rake任务中使用invoke "my_namespace:my_task"而不是Rake::Task[ "my_namespace:my_task" ].invoke

您在模块中共享方法,并将此类模块放在lib文件夹中。

类似lib/fake_data.rb东西

module FakeData
  def random_address
    [Faker::Address.street_address, Faker::Address.city].join("\n")
  end

  module_function 
end

在你的rake任务中只需要模块,然后调用FakeData.random_address

但是,如果它就像你每次运行测试时需要做的种子一样,你应该考虑将它添加到你的将军before all

例如,我的spec_helper看起来像这样:

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

RSpec.configure do |config|
  config.use_transactional_fixtures = true
  config.infer_base_class_for_anonymous_controllers = false
  config.order = "random"

  include SetupSupport

  config.before(:all) do
    load_db_seed
  end
end

模块SetupSupportspec/support/setup_support.rb定义,如下所示:

module SetupSupport

  def load_db_seed
    load(File.join(Rails.root, 'db', 'seeds.rb'))
  end

end

不确定是否需要加载种子,或者已经这样做了,但这也是生成所需假数据的理想位置。

请注意,我的设置支持类是在spec/support定义的,因为代码只与我的规范相关,我没有rake任务也需要相同的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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