RSpec Tips

Wanna test your Rails app, but new to RSpec? Here’s a couple of tips I’ve put together for you:

 

Advertisements

How to locate missing test files in your Rails app

Wanna make sure you have each of your controllers, models, templates, etc.. all have corresponding tests? I wrote a little bash script to make sure each class has its own spec file. Simple yet effective :). For more in-depth analysis, try a complete code-coverage tool like https://github.com/colszowka/simplecov.

spec/untested.sh:

#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
#echo $DIR

echo ""
echo "Untested Controllers"
echo "===================="
CONTROLLERS="$(find -E "${DIR}/../app/controllers" -iregex ".*\.rb")"
for f in $CONTROLLERS;
do
        CONTROLLER=${f##*/}
        SPEC=${CONTROLLER/.rb/_spec.rb}
        FOUND="$(find "${DIR}" -path "*${SPEC}")"
        if [[ $FOUND == "" ]]; then
                echo "-${CONTROLLER}"
        fi
done

echo ""
echo "Untested Models"
echo "==============="
MODELS="$(find -E "${DIR}/../app/models" -iregex ".*\.rb")"
for f in $MODELS;
do
        MODEL=${f##*/}
        SPEC=${MODEL/.rb/_spec.rb}
        FOUND="$(find "${DIR}" -path "*${SPEC}")"
        if [[ $FOUND == "" ]]; then
                echo "-${MODEL}"
        fi
done

echo ""
echo "Untested Templates"
echo "=================="
TEMPLATES="$(find -E "${DIR}/.." -iregex ".*(_default|_builder|_player).rabl")"
for f in $TEMPLATES;
do
        TEMPLATE=${f##*/views/}
        SPEC=${TEMPLATE/.rabl/_spec.rb}
        #echo $SPEC
        FOUND="$(find "${DIR}" -path "*${SPEC}")"
        #echo $FOUND
        if [[ $FOUND == "" ]]; then
                echo "-${TEMPLATE}"
        fi
done

echo ""