背景:我遇到了Thoughtbot的“Factory Girl”宝石的一些问题,用于创建在单位和其他测试中使用的对象。我想去控制台并运行不同的Factory Girl电话来查看发生了什么。例如,我想进去那里做...
>> Factory(:user).inspect
我知道你可以在不同的环境中运行控制台......
$ script / console RAILS_ENV = test
但是当我这样做时,工厂课程不可用。看起来好像test_helper.rb
没有加载。
我尝试了各种require
调用,其中包括test_helper.rb
的绝对路径,但它们的失败与此类似:
$ script/console RAILS_ENV=test
>> require '/Users/ethan/project/contactdb/test/test_helper.rb'
Errno::ENOENT: No such file or directory -
/Users/ethan/project/contactdb/config/environments/RAILS_ENV=test.rb
格儿。哎呀。
对于Rails <3.0
运行script/console --help
。您会注意到语法是script/console [environment]
,在您的情况下是script/console test
。
我不确定您是否需要测试帮助程序,或者测试环境是否为您执行此操作,但使用该命令,您至少应该能够成功启动到测试环境中。
作为旁注:脚本中的各种二进制文件具有不同的设置rails环境的方式确实有点奇怪。
对于Rails 3和4
运行rails c test
。如果您需要在当前应用环境中使用此功能,请预先添加bundle exec
。
对于Rails 5和6
运行rails console -e test
。
运行rails控制台测试环境的命令是
rails c -e test
要么
RAILS_ENV=test rails c
如果你遇到类似的问题
ActiveRecord::StatementInvalid:
Mysql2::Error: Table 'DB_test.users' doesn't exist: SHOW FULL FIELDS FROM `users`
那么你应该首先通过运行来准备你的测试数据库
bundle exec rake db:test:prepare
在Rails 3中,只需执行rails console test
或rails console production
或rails console development
(这是默认设置)。
script/console test
应该是你所需要的一切。
对于Rails 5.2.0:“不推荐将环境名称作为常规参数传递,并将在下一个Rails版本中删除。请改用-e选项。”
rails c -e test
您可以指定控制台命令应在其中运行的环境。
rails c [environment]
例子
1)用于分期
rails c staging
2)用于生产
rails c production
有关来源和详细说明:The Rails Command Line
大卫史密斯是正确的,只是做
script/console test
help命令将显示其工作原理:
$ script/console -h
Usage: console [environment] [options]
-s, --sandbox Rollback database modifications on exit.
--irb=[irb] Invoke a different irb.
--debugger Enable ruby-debugging for the console.
这是[环境]位。
我分享了提问者的痛苦。这里有三个单独的问题,其中一些是解决的问题,一些不是:
bundle exec rails c test
或其替代语法。require './test/test_helper'
这样的东西应该这样做。
对我来说,这返回true,表示我在启动控制台时尚未加载它。如果该语句返回false,那么你只是浪费了几次击键,但你还是很高兴。ActiveSupport::TestCase.new("no idea what this is for").create_user
确保安装了GEM,并在environment.rb或test.rb文件中添加了以下行。
config.gem "thoughtbot-factory_girl", :lib => "factory_girl", :source => "http://gems.github.com"
测试环境
rails console test # or just rails c test
发展环境
rails console # or just rails c