Load and use fixture in rails console

前端 未结 6 1821
南方客
南方客 2021-01-31 08:07

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 ha

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-31 08:41

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

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

    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")
    

    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")
    

    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'.

提交回复
热议问题