gpt4 book ai didi

ruby - 在 rspec(和 cucumber )中测试 rake 任务

转载 作者:数据小太阳 更新时间:2023-10-29 06:37:17 25 4
gpt4 key购买 nike

我是 Ruby 的新手,我一直在尝试学习 Rake、RSpec 和 Cucumber。我找到了一些可以帮助我测试 Rake 任务的代码,但我无法让它正常工作。有人告诉我:http://blog.codahale.com/2007/12/20/rake-vs-rspec-fight/放弃这个:

def describe_rake_task(task_name, filename, &block)
require "rake"

describe "Rake task #{task_name}" do
attr_reader :task

before(:all) do
@rake = Rake::Application.new
Rake.application = @rake
load filename
@task = Rake::Task[task_name]
end

after(:all) do
Rake.application = nil
end

def invoke!
for action in task.instance_eval { @actions }
instance_eval(&action)
end
end

instance_eval(&block)
end
end

进入我的 spec_helper.rb 文件。

我已经设法取出这段代码并在我的 cucumber 步骤中运行它,如下所示:

When /^I run the update_installers task$/ do
@rake = Rake::Application.new
Rake.application = @rake
load "lib/tasks/rakefile.rb"
@task = Rake::Task["update_installers"]

for action in @task.instance_eval { @actions }
instance_eval(&action)
end

instance_eval(&block)

Rake.application = nil
end

但是当我尝试在 rspec 中运行时,出现以下错误。

ArgumentError in 'Rake task install_grapevine should install to the mygrapevine directory'

wrong number of arguments (1 for 2) /spec/spec_helper.rb: 21:in instance_eval'
/spec/spec_helper.rb: 21:in
block in invoke!' /spec/spec_helper.rb: 20:in each'
/spec/spec_helper.rb: 20:in
invoke!' /spec/tasks/rakefile_spec.rb:12:in `block (2 levels) in '

不幸的是,我已经使用了不到一周的 ruby​​,所以元编程的东西超出了我的理解范围。谁能指出我正确的方向?

最佳答案

这对我有用:(Rails3/Ruby 1.9.2)

When /^the system does it's automated tasks$/ do    
require "rake"
@rake = Rake::Application.new
Rake.application = @rake
Rake.application.rake_require "tasks/cron"
Rake::Task.define_task(:environment)
@rake['cron'].invoke
end

在此处替换您的 rake 任务名称,并注意如果您的加载路径中没有 lib 文件夹,则您的要求可能是“lib/tasks/cron”。

我同意你应该只在 Rake 任务中做最少的工作,并将其余的工作推到模型中以便于测试。话虽如此,我认为在集成测试期间确保代码在我的 cron 任务中实际运行很重要,因此我认为对 rake 任务进行非常温和的测试是合理的。

关于ruby - 在 rspec(和 cucumber )中测试 rake 任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2613533/

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