Automatically Measuring Your Code Coverage Using Selenium (or Watir) and Rcov

desc "Measure coverage of selenium specs"
task :coverage do
  FileUtils.rm_rf "selenium_coverage"
  mongrel_pid = fork { exec("rcov script/server -o selenium_coverage --rails -- -e test -p 4000") }
  sleep(6) # wait for mongrel to start

  begin # selenium will call "exit 1" if there are failures
    Rake::Task["selenium:spec"].invoke
  rescue SystemExit; end

  Process.kill("INT", mongrel_pid) # triggers generation of rcov report
  Process.wait
  system("open selenium_coverage/index.html") if PLATFORM['darwin']
end

CustomMaintenancePages

January05,2007

Update:TheAdvancedRailsRecipesbookincludesanupdatedandextendedversionofthisrecipe.Thanksforyoursupport!

Capistranomakesitquickandeasytoputupatemporarymaintenancepagewhileyou'redoingchoresaroundyourproductionRailsapp.Hopefullyuserswon'tseethatpageforlong,butevenwhentheydoit'sanicetouchtocustomizethepageasmidge.

ThestockmaintenancepagetemplatethatCapistranousesbydefaultisgood,butit'seasytosetyourappapartfromtherest.Simplyredefinethedisable_webtaskinyourdeploy.rbfiletorenderacustomtemplate.Here'sanexample:

task:disable_web,:roles=>:webdo

on_rollback{delete"#{shared_path}/system/maintenance.html"}

maintenance=render("./app/views/layouts/maintenance.rhtml",

:deadline=>ENV['UNTIL'],

:reason=>ENV['REASON'])

putmaintenance,"#{shared_path}/system/maintenance.html",

:mode=>0644

end

ThistaskusesERbtorenderyourlocalmaintenance.rhtmltemplate,andtransferstheresulttothemaintenance.htmlfileonallremotehostsinthewebrole.

Itendtoputthemaintenance.rhtmltemplateinthelayoutsdirectorybecauseit'safullHTMLfileliketheotherlayoutfiles,notjustafragmentofHTML.Here'sanexamplemaintenance.rhtmltemplate,sansallthesurroundingHTML:

<h1>

We'recurrentlydownfor<%=reason?reason:"maintenance"%>

asof<%=Time.now.strftime("%H:%M%Z")%>.

</h1>

<p>

Sorryfortheinconvenience.We'llbeback

<%=deadline?"by#{deadline}":"shortly"%>.

Pleaseemailusifyouneedtogetintouch.

</p>

You'llalsoneedtotellyourwebservertocheckforthestaticmaintenancefileandredirectallrequeststoitifthefileexists.Here'sanexampleforApache:

RewriteCond%{REQUEST_URI}!\.(css|jpg|png)$

RewriteCond%{DOCUMENT_ROOT}/system/maintenance.html-f

RewriteCond%{SCRIPT_FILENAME}!maintenance.html

RewriteRule^.*$/system/maintenance.html[L]

Then,whenit'stimeforsomeappmaintenance,youcanputupyourcustommaintenancepagebytyping

capdisable_web

Here'sanexampleofwhatyou'dseeifwewerecleaningoutthedustbunniesononeofourapps:

Maintenance

Andwhenyou'vefinished,simplytakedownthemaintenancepagebytyping

capenable_web

Anotherbenefitofredefiningdisable_webandusingacustomtemplateisbeingabletodefineinanyvariablesyoulike.Here'showyou'dpassinthetwovariablesusedinthetemplateabove,butyoucanimaginedefininganarbitrarynumberofvariables:

UNTIL="16:00MST"REASON="adatabaseupgrade"capdisable_web

Ideallyyoursitewouldneverbedown,butonceinawhileyouneedtodosomepreventativemaintenance.Peoplewhouseyourappwillappreciatethatyou'vetakenthetimetospruceuptheedgecases.

rcovRakeTask

January05,2007

Jamisrecentlypostedatiponthevirtuesofrunningrcovtomeasurecodecoverage.Whileit'seasytoputtoomuchfaithincodecoverage,runningrcovisaninexpensivewaytogetsomeinsightintoyourtestingpatterns.I'vebeenusingitonrecentRailsprojectstogetaquicksynopticviewofthetestlandscape.

Ifyou'dliketogivercovatry,herearethestepsIusedtogetitworking:

1.Installrcov

geminstallrcov

2.WriteaRakeTask

Addthistasktoyourlib/tasks/my_app.rakefile,forexample:

namespace:testdo

desc'Measurestestcoverage'

task:coveragedo

rm_f"coverage"

rm_f"coverage.data"

rcov="rcov--rails--aggregatecoverage.data--text-summary-Ilib"

system("#{rcov}--no-htmltest/unit/*_test.rb")

system("#{rcov}--no-htmltest/functional/*_test.rb")

system("#{rcov}--htmltest/integration/*_test.rb")

system("opencoverage/index.html")ifPLATFORM['darwin']

end

end

I'vetriedvariousapproachesandoptionsoverthelastfewmonths,andtheseseemtoworkbestforme.Theresultsforalltheunit,functional,andintegrationtestsgetaggregatedintoonereportsoIcanscaneverythingquickly.Yourmileagemayvary.

3.RuntheTask

raketest:coverage

You'llgetatextsummaryfortheunit,functional,andintegrationtestsasthey'rebeingrun.Andifyou'reonaMac,thetaskautomaticallypopsopentheHTMLreportinyourdefaultbrowserattheend.Otherwise,youcanopenitmanually.

Enjoy!