Vik*_*tor 5 ruby rubygems ruby-on-rails cucumber aruba
我正在制作一个执行 Rails 命令的 gem(rails g model Item例如)。当我在 Rails 项目中使用它时,一切正常。问题是在 Rails 项目之外的开发中对其进行测试。
我正在使用cucumberwitharuba来测试 CLI 命令是否执行正确的 Rails 命令并生成预期的文件。不幸的是,当我尝试测试该行为时,它失败了,因为没有 Rails 文件,并且命令需要在 Rails 项目内部运行才能工作。
我已向 gemspec 添加了 Rails 依赖项:
Gem::Specification.new do |spec|
spec.add_development_dependency 'rails', '~> 5.2.4'
end
Run Code Online (Sandbox Code Playgroud)
我考虑过在测试开始时创建一个新的 Rails 项目,然后在测试运行后删除它,但这似乎非常不方便。有一个更好的方法吗?
在运行测试之前,我们用于WickedPDF的默认rake任务是删除并在 gem 的 gitignored 子目录中生成完整的 Rails 应用程序。
作为此 Rakefile 的高级简化示例,它看起来像这样:
耙文件
require 'rake'
require 'rake/testtask'
# This gets run when you run `bin/rake` or `bundle exec rake` without specifying a task.
task :default => [:generate_dummy_rails_app, :test]
desc 'generate a rails app inside the test directory to get access to it'
task :generate_dummy_rails_app do
if File.exist?('test/dummy/config/environment.rb')
FileUtils.rm_r Dir.glob('test/dummy/')
end
system('rails new test/dummy --database=sqlite3')
system('touch test/dummy/db/schema.rb')
FileUtils.cp 'test/fixtures/database.yml', 'test/dummy/config/'
FileUtils.rm_r Dir.glob('test/dummy/test/*') # clobber existing tests
end
desc 'run tests in the test directory, which includes the generated rails app'
Rake::TestTask.new(:test) do |t|
t.libs << 'lib'
t.libs << 'test'
t.pattern = 'test/**/*_test.rb'
t.verbose = true
end
Run Code Online (Sandbox Code Playgroud)
然后,在test/test_helper.rb中,我们需要生成的 Rails 应用程序,它会加载Rails自身及其环境:
测试/test_helper.rb
ENV['RAILS_ENV'] = 'test'
require File.expand_path('../dummy/config/environment.rb', __FILE__)
require 'test/unit' # or possibly rspec/minispec
# Tests can go here, or other test files can require this file to have the Rails environment available to them.
# Some tests may need to copy assets/fixtures/controllers into the dummy app before being run. That can happen here, or in your test setup.
Run Code Online (Sandbox Code Playgroud)
您可以通过自定义生成应用程序的命令来跳过不需要的 Rails 部分。例如,默认情况下,您的 gem 可能根本不需要数据库或很多东西,因此可以为更简单的应用程序自定义命令。也许是这样的:
system("rails new test/dummy --skip-active-record \
--skip-active-storage --skip-action-cable --skip-webpack-install \
--skip-git --skip-sprockets --skip-javascript --skip-turbolinks")
Run Code Online (Sandbox Code Playgroud)
在 WickedPDF 项目中,我们想要测试各种“默认”Rails 安装,因此我们没有太多自定义命令,但这可能会生成比测试某些生成器任务所需的更多内容。
WickedPDF 还使用 TravisCI和多个 Gemfiles测试多个版本的 Rails ,但这也可以通过Luke 在本线程中建议的Appraisal gem来完成。
| 归档时间: |
|
| 查看次数: |
755 次 |
| 最近记录: |