Rails:让这个 rake 任务知道它处于测试环境中
我在 lib/tasks
文件夹中定义了以下 rake 任务:
namespace :db do
namespace :test do
task :prepare => :environment do
Rake::Task["db:seed"].invoke
end
end
end
现在,它的作用是在运行 rake db:test:prepare
时为测试数据库播种。我这样做是因为我有一些必须存在的基本记录才能使应用程序正常运行,因此它们不是可选的,也不能真正被嘲笑。
另外,我有一个在开发和生产中使用 S3 进行资产存储的模型,但我不希望它使用 S3 进行测试。我在模型中设置了一个方法,将存储路径从 S3 更改为本地 if Rails.env.test?
但是,这不起作用。我想知道 rake 任务是否知道它是从什么环境中调用的,但事实证明它不是。我将其放在 seeds.rb 文件的顶部:
puts "Environment Check: Rails Environment = #{Rails.env}"
果然,当任务运行时会打印: Environment Check: Rails Environment =development
那么,我如何重做这个 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
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.
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?
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}"
Sure enough, when the task runs this prints: Environment Check: Rails Environment = development
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??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我也遇到这个问题;在我的 db/seeds.rb 文件中,我有一个在开发环境中创建用户帐户的块,但在准备测试环境以运行 rake 时也会创建它们RSpec 或 Cucumber 测试,结果是红色的墙。
更新:我发现为 rake 任务指定环境的最佳方法是在任务中指定环境,首先是需要设置环境的语句。所以在这种情况下:
完成工作。
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 runrake
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:
does the job.
通过阅读 db:test 任务的源代码,看起来他们只关心从database.yml中获取测试数据库信息,但不关心他们在哪个实际环境下执行此操作。
您可能需要运行 rake db:test:prepare RAILS_ENV=test 以确保您处于测试环境下。
From reading the db:test tasks's source, it looks like they only care about grabbing the test db info from database.yml, but don't care which actual environment they're doing it under.
You might need to run rake db:test:prepare RAILS_ENV=test to ensure you're under the test environment.