在Rails控制台中加载和使用夹具 [英] Load and use fixture in rails console

查看:74
本文介绍了在Rails控制台中加载和使用夹具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以在Rails控制台中加载和/或使用固定装置.实际上,我想从夹具users.yml创建一个用户来进行一些测试,而不必每次都经历做User.new(:name = "John", :email = "..")的所有痛苦".
我目前处于测试环境(rails c RAILS_ENV=test).

I wonder if there's a way to load and/or use fixture in rails console. Actually, I'd like to create a user from my fixture users.yml to do some testing without having to go through all the "pain" of doing User.new(:name = "John", :email = "..") each time.
I am currently in test environment (rails c RAILS_ENV=test).

如果这不是处理问题的好方法,请说出来.我是Rails的新手,所以我在这里学习:)

If it's not a good way to do things, please say it. I'm new to Rails so I'm here to learn :)

推荐答案

您应该能够在进入控制台之前加载设备.像这样:

You should be able to load your fixtures prior to entering console. Like this:

bin/rails db:fixtures:load RAILS_ENV=test
rails console test

但是,您仍然无法像在测试中那样访问灯具数据.这只是将夹具数据加载到测试数据库中.因此,您仍然必须做类似的事情:

However, you still won't be able to access your fixture data like you would in a test. This simply loads your test database with your fixtures data. So you'd still have to do something like:

user = User.find_by(name: "John")

但是,您仍然可以为这种事情创建快捷方式.您可以将任何想要的红宝石代码添加到〜/.irbrc中.我建议按照此处所述创建.railsrc文件.然后,您可以设置以下内容:

But, you can still create shortcuts for this sort of thing. You can add any ruby code you'd like to your ~/.irbrc. I suggest creating a .railsrc file as described here. You can then set up things like:

john = User.find_by(name: "John")

因此,现在您可以在加载控制台后开始引用变量"john".顺便说一句,我链接到的帖子显示了如何设置全局.railsrc文件,但是您可以对其进行设置,以使每个项目都具有.railsrc文件.或者,如果您想要一些花哨的东西,但是很容易做...只需在您的项目中创建一个ruby文件(也许是"shortcuts.rb").加载控制台后,只需执行快捷方式"即可.

So now you can just start referring to the variable 'john' after console loads. Incidentally, the post I linked to shows how to set up a global .railsrc file, but you could set it up so that you had a per project .railsrc. Or, if you want something a little less fancy, but easy to do... just create a ruby file in your project (maybe 'shortcuts.rb'). After console is loaded, just do a require 'shortcuts'.

这篇关于在Rails控制台中加载和使用夹具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆