How to run Rails console in the test environment and load test_helper.rb?

后端 未结 10 677
梦如初夏
梦如初夏 2020-12-12 19:58

The background: I\'m having some problems with Thoughtbot\'s \"Factory Girl\" gem, with is used to create objects to use in unit and other tests. I\'d like to go to the cons

相关标签:
10条回答
  • 2020-12-12 20:44

    For Rails < 3.0

    Run script/console --help. You'll notice that the syntax is script/console [environment], which in your case is script/console test.

    I'm not sure if you have to require the test helper or if the test environment does that for you, but with that command you should at least be able to boot successfully into the test env.

    As a sidenote: It is indeed kind of odd that the various binaries in script/ has different ways of setting the rails environment.

    For Rails 3 and 4

    Run rails c test. Prepend bundle exec if you need this for the current app environment.

    For Rails 5 and 6

    Run rails console -e test.

    0 讨论(0)
  • 2020-12-12 20:44

    Command to run rails console test environment is

    rails c -e test
    

    or

    RAILS_ENV=test rails c
    

    if you are facing problem something like

    ActiveRecord::StatementInvalid:
       Mysql2::Error: Table 'DB_test.users' doesn't exist: SHOW FULL FIELDS FROM `users`
    

    then you should first prepare your test DB by running

    bundle exec rake db:test:prepare
    
    0 讨论(0)
  • 2020-12-12 20:45

    David Smith is correct, just do

    script/console test
    

    The help command will show why this works:

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

    It's the [environment] bit.

    0 讨论(0)
  • 2020-12-12 20:46

    For Rails 5.2.0: "Passing the environment's name as a regular argument is deprecated and will be removed in the next Rails version. Please, use the -e option instead."

    rails c -e test
    
    0 讨论(0)
提交回复
热议问题