有没有人能指出来,在Docker容器内(在容器构建/运行期间)运行Rails API应用程序的RSpec测试的最佳方法是什么?
目的是能够将开发环境与其他环境分离,并仅在development
模式下运行测试,在staging、production
环境中仅启动Puma服务器。
bundle exec rspec
命令放置的正确位置是什么,- 在单独的entrypoint.sh
脚本中,直接在Dockerfile
、docker-compose.yml
文件中,还是其他解决方案?
所有谷歌的结果以及PragProg的Docker for Rails Developers书籍都没有示例,唯一的运行测试的方式是针对已经运行的容器运行它们。
实际上,我的Dockerfile
看起来像这样:
FROM ruby:2.6.1
RUN apt-get update -yqq
RUN apt-get install -yqq --no-install-recommends build-essential zip unzip libpq-dev libaio1 libaio-dev nodejs
ENV APP_HOME=/usr/src/app
ENV BUNDLE_PATH /gems
COPY . $APP_HOME
RUN echo "gem: --no-rdoc --no-ri" >> ~/.gemrc
WORKDIR $APP_HOME
RUN gem update --system
RUN gem install bundler
RUN bundle install
RUN ["chmod", "+x", "entrypoint.sh"]
CMD ["./entrypoint.sh"]
entrypoint.sh
的内容如下:
#!/bin/bash
set -e
if [ -f tmp/pids/server.pid ]; then
rm tmp/pids/server.pid
fi
./wait-for-it.sh ${DATABASE_HOST}:${DATABASE_PORT}
if [ -z "$RAILS_ENV" ]; then
echo "RAILS_ENV variable is not set, will use development by default"
bundle exec rails db:reset
bundle exec rails db:migrate
bundle exec rspec
else
bundle exec rails s -e $RAILS_ENV -p 3000 -b 0.0.0.0
fi
最后,docker-compose.yml
文件:
version: '3.3'
services:
api:
build: ../..
ports:
- '3000:3000'
volumes:
- .:/usr/src/app
- gem_cache:/gems
env_file:
- ./env/database.env
- ./env/web.env
depends_on:
- database
# Keeps the stdin open, so we can attach to our app container's process and
# do stuff such as `byebug` or `binding.pry`:
stdin_open: true
# Allows us to send signals (CTRL+C, CTRL+P + CTRL+Q) into the container
tty: true
database:
image: postgres:9.6
env_file:
- ./env/database.env
volumes:
- db-data:/var/lib/postgresql/data
ports:
- 5432:5432
volumes:
db-data:
gem_cache: