问题描述
我在lib/tasks
文件夹中定义了以下rake任务:
I have the following rake task defined in my lib/tasks
folder:
namespace :db do
namespace :test do
task :prepare => :environment do
Rake::Task["db:seed"].invoke
end
end
end
现在,这是在我运行rake db:test:prepare
时播种测试数据库的种子.之所以这样做,是因为我有一些基本记录,这些记录才能使该应用程序正常运行,因此它们不是可选的,并且不能真正被嘲笑.
Now, what this does is seed the test DB when I run rake db:test:prepare
. I do this because I have some basic records that must exist in order for the app to function, so they're not optional and can't really be mocked.
另外,我有一个模型,该模型在开发和生产中使用S3进行资产存储,但是我不希望它使用S3进行测试.我已经在模型中设置了一个方法,如果Rails.env.test?
Separately, I have a model that uses S3 for asset storage in development and production, but I don't want it to use S3 for testing. I have set up a method in the model that changes the storage path from S3 to local if Rails.env.test?
但是,这不起作用.我想知道rake任务是否知道从哪个环境中调用它,而事实并非如此.我把它放在了seed.rb文件的顶部:
However, this isn't working. I was wondering if the rake task was aware of what environment it was being called from, and it turns out it is NOT. I put this at the top of my seeds.rb file:
puts "Environment Check: Rails Environment = #{Rails.env}"
果然,当任务运行时,此打印:Environment Check: Rails Environment = development
Sure enough, when the task runs this prints: Environment Check: Rails Environment = development
因此,我该如何重做此rake任务,以便当它为测试数据库植入种子时,它知道它为测试数据库植入了种子?
So, how can I redo this rake task so that when it's seeding the test DB it knows that it's seeding the test DB??
推荐答案
我也遇到了这个问题;在我的db/seeds.rb
文件中,我有一个块,可以在开发环境中创建用户帐户,但是在准备测试环境以运行rake
进行RSpec或Cucumber测试时也会创建用户帐户,这导致一堵墙.
I was having this problem too; in my db/seeds.rb
file I have a block that creates user accounts in the development environment, but they were also being created when preparing the test environment to run rake
for RSpec or Cucumber testing, which resulted in a wall of red.
已更新:我发现是在任务中指定环境,首先是需要设置环境的所有语句.因此,在这种情况下:
Updated: I've found that the best way to specify the environment for rake tasks is to specify the environment within the task, above all statements that need the environment to be set. So in this case:
Rails.env = 'test'
Rake::Task["db:seed"].invoke
完成工作.
这篇关于Rails:使此rake任务意识到它在测试环境中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!