08 Jun 2012

Testing the asset pipeline before deploying to production

I hate when I deploy to production only to discover that the application fails because an error in the assets pipeline, usually because something is not precompiled.

In order to test locally that the asset pipeline is properly set up and to avoid surprises later, I wrote the following script. Before using it, you have to update config/database.yml and add a staging config. The script is self-explanatory:

    #!/bin/bash
    PID_FILE=tmp/pids/smoketests.pid

    prepare_environment() {
        export RAILS_ENV=staging
        cp config/environments/production.rb config/environments/staging.rb
        sed -i -e's/\(config\.serve_static_assets.*= \)false/\1true/g' config/environments/staging.rb
    }

    launch_server() {
        echo "Launching server..."
        rm log/staging.log
        exec rails s --pid $PID_FILE &>/dev/null &
        sleep 3s
    }

    kill_server() {
        echo "Killing server..."
        kill -9 `cat $PID_FILE`
    }

    migrate_db() {
        echo "Migrating staging db..."
        RAILS_ENV=staging bundle exec rake db:migrate > /dev/null
    }

    compile_assets() {
        echo "Compiling assets..."
        bundle exec rake assets:precompile &> /dev/null
    }

    make_requests() {
        echo "Requesting webpage..."
        wget http://localhost:3000 --quiet -O /dev/null
        # add more requests here if needed
    }

    check_errors() {
        errors_found=`cat log/staging.log | grep Error`
        if [ -n "$errors_found" ]; then
            echo -e "\033[31m* Errors found:"
            echo "$errors_found"
        else
            echo -e "\033[32m* No errors! Ready to deploy!"
        fi

        echo -e "\033[0m"
    }

    prepare_environment
    migrate_db
    compile_assets

    launch_server
    make_requests
    kill_server

    check_errors

_prepareenvironment() makes a copy of the production environment config and changes the property config.serve_static_assets to true so Webbrick serves static assets.