Gitlab CI - deploy to Heroku and run migrations

The information in this answer may be out of date. Please see both answers below, and remember to upvote the answers that are up to date to help future visitors.

here is a sample .yml I have that runs my tests then pushed to Heroku stage (for master branch pushes) or production (for tags pushes)

image: "ruby:2.3"

test:
  script:
  - apt-get update -qy
  - apt-get install -y nodejs
  - gem install bundler
  - bundle install -j $(nproc) --without production
  - bundle exec rails db:create RAILS_ENV=test
  - bundle exec rails db:migrate RAILS_ENV=test
  - bundle exec rails RAILS_ENV=test

staging:
  type: deploy
  environment: staging
  script:
  - gem install dpl
  - dpl --provider=heroku --app=$HEROKU_STAGING_APP_NAME --api-key=$HEROKU_API_KEY
  - "curl -n -X POST https://api.heroku.com/apps/$HEROKU_STAGING_APP_NAME/ps -H \"Accept: application/json\" -H \"Authorization: Bearer ${HEROKU_API_KEY}\" -d \"command=bundle exec rails db:migrate\""
  only:
  - master

production:
  type: deploy
  environment: production
  script:
  - gem install dpl
  - dpl --provider=heroku --app=$HEROKU_PRODUCTION_APP_NAME --api-key=$HEROKU_API_KEY
  - "curl -n -X POST https://api.heroku.com/apps/$HEROKU_PRODUCTION_APP_NAME/ps -H \"Accept: application/json\" -H \"Authorization: Bearer ${HEROKU_API_KEY}\" -d \"command=bundle exec rails db:migrate\""
  only:
  - tags

If you want to be able to use the full power of the Heroku CLI in your GitLab CI process (including having the build fail if a migration fails for whichever reason), you can also try this approach which will install the Heroku CLI and deliver status codes of your Heroku commands back to GitLab, as well as, of course, the command line output. Using heroku run without credentials on the commandline require the HEROKU_API_KEY environment variable to be set to a key which has access to the app in question.

before_script:
  - echo "deb http://toolbelt.heroku.com/ubuntu ./" > /etc/apt/sources.list.d/heroku.list
  - wget -O- https://toolbelt.heroku.com/apt/release.key | apt-key add -
  - apt-get update
  - apt-get install -y heroku-toolbelt
  - gem install dpl

stages:
  - deploy

test_on_heroku:
  type: deploy
  script:
    - dpl --provider=heroku --app=my_heroku_app --api-key=$HEROKU_API_KEY
    - heroku run <your command here> --exit-code --app my_heroku_app

I actually run my tests on an Heroku instance to be sure, the environment is exactly the same. This is where this comes in real handy.