KEMBAR78
RSpec and Rails | PPTX
RSpec and RailsAlan Hechthttp://alanhecht.me
InstallationRSpec 2.5Only works with Rails 3rspec and rspec-railsgem install rspec-railsWhat if you’re using Rails 2.x?Need to install RSpec 1.3
Creating a Rails Projectrails new cart_rspecEdit the Gemfilebundle installrails generate rspec:install
Railswizard.orgRailswizard.org allows you to specify options when creating a Rails 3 projectRails 3 allows for flexibility in what’s usedDatabase/ORM ActiveRecord, MongomapperUnit Testing FrameworkTestUnit, RspecJavaScript FrameworkjQuery, Prototype
Set up the projectUse railswizard to create a templateWe’ll be creating the shopping cartCreate rvmrc filebundle installGit setup
Set up the Product & CartGenerate product scaffoldingGenerate cart scaffoldingGenerate line_item scaffoldingRSpec tests were created with scaffoldingCommit changes
RSpec - Models
Run TestsUpdate databaserake db:migrateRun RSpecrake spec
RSpec OptionsIn .rspec fileDocumentation format--format docHTML format--format html:/path/to/file
RSpec – ModelsMost similar to using RSpec without RailsEverything we learned from the calculator example appliesBusiness logic testing should take place in the models
RSpec - Models
RSpec – FixturesFixture files go in spec/fixturesNeed to explicitly load fixtures Can load all the fixtures for testsAdd ‘config.global_fixtures = true’ to spec_helper.rb
RSpec - ControllersIn Rails Test::Unit, Controllers and Views tested together in functional testsFor RSpec, each is tested separatelyOuter describe contains the controller classNeeded to run the testsDescribe in each test has controller actionDoesn’t affect the test, only by convention
Controller MatchersRSpec has matchers specifically for controller testing:response.should be_successresponse.should be_redirectresponse.should redirect_to(url)response.should render_template(‘app/views/products/index’)response.should render_template(:partial => “show_cart”)
Controllers - Example
Stubs – What are they?A fake object that returns a pre-determined value for a method callActual object is not calledStubs and mocks often used interchangeablyMean two different thingsBut people generally refer to “Mock Object Frameworks”
Stubs – Why?Separation of concernsController doesn’t depend on modelModels don’t depend on each otherEach model can be tested in isolationDon’t need the database for testingFaster testsCould use stubs to simulate a network or web service response
Stubs – ImplicationsNeed to have integration testsAll of your tests could pass, but the site may not functionWebrat (used by Cucumber) & Capybara are two such integration tools
MocksJust like Stubs, but with an expectation to be (or not to be) calledTest will fail if the mock is (or isn’t) calledUsed in the same way as stubs
RSpec - ViewsVerify the presence of fields on the viewAvoid relying on the layout of the viewView could break from a design changeBut good for testing groups of elements with a common purpose (like options fields that expand or hide)Use XPath or CSS selectors to locate tagsStrongly recommend CSS selectors
RSpec - Views
RSpec - ViewsDescribe contains view pathOptional but usefulIf ‘render’ doesn’t contain arguments, use the comment on the describe line
Test Coveragercov gem will show you how much of your code has been testedrake spec:rcovBy default, all tests are runNeed to modify Rakefile to cover only specific areas like models & viewsOutput is in the <project>/coverage directoryHTML viewable in a browserOpen coverage/index.html
RCov - Output
RCov - TipsNo need to try for 100% test coverageGood goal would be around 70 – 80%
Automatic TestingAutotest monitors changes to files in your projectEvery time a test is saved, the test is re-runEverytime app code is saved, corresponding test is rungem install autotest & autotest-rails-pureCreate an autotest directorydiscover.rb
Autotest – TipsBe careful when using on a laptopAutotest polls for changesYou’ll either get burnt by a hot laptop or your battery will die, whichever comes firstOn OS X, you can install autotest-fsevent, the file system change triggers autotest executionGrowl notificationsautotest-growlAdd to rails root .autotest file

RSpec and Rails

  • 1.
    RSpec and RailsAlanHechthttp://alanhecht.me
  • 2.
    InstallationRSpec 2.5Only workswith Rails 3rspec and rspec-railsgem install rspec-railsWhat if you’re using Rails 2.x?Need to install RSpec 1.3
  • 3.
    Creating a RailsProjectrails new cart_rspecEdit the Gemfilebundle installrails generate rspec:install
  • 4.
    Railswizard.orgRailswizard.org allows youto specify options when creating a Rails 3 projectRails 3 allows for flexibility in what’s usedDatabase/ORM ActiveRecord, MongomapperUnit Testing FrameworkTestUnit, RspecJavaScript FrameworkjQuery, Prototype
  • 5.
    Set up theprojectUse railswizard to create a templateWe’ll be creating the shopping cartCreate rvmrc filebundle installGit setup
  • 6.
    Set up theProduct & CartGenerate product scaffoldingGenerate cart scaffoldingGenerate line_item scaffoldingRSpec tests were created with scaffoldingCommit changes
  • 7.
  • 8.
    Run TestsUpdate databaserakedb:migrateRun RSpecrake spec
  • 9.
    RSpec OptionsIn .rspecfileDocumentation format--format docHTML format--format html:/path/to/file
  • 10.
    RSpec – ModelsMostsimilar to using RSpec without RailsEverything we learned from the calculator example appliesBusiness logic testing should take place in the models
  • 11.
  • 12.
    RSpec – FixturesFixturefiles go in spec/fixturesNeed to explicitly load fixtures Can load all the fixtures for testsAdd ‘config.global_fixtures = true’ to spec_helper.rb
  • 13.
    RSpec - ControllersInRails Test::Unit, Controllers and Views tested together in functional testsFor RSpec, each is tested separatelyOuter describe contains the controller classNeeded to run the testsDescribe in each test has controller actionDoesn’t affect the test, only by convention
  • 14.
    Controller MatchersRSpec hasmatchers specifically for controller testing:response.should be_successresponse.should be_redirectresponse.should redirect_to(url)response.should render_template(‘app/views/products/index’)response.should render_template(:partial => “show_cart”)
  • 15.
  • 16.
    Stubs – Whatare they?A fake object that returns a pre-determined value for a method callActual object is not calledStubs and mocks often used interchangeablyMean two different thingsBut people generally refer to “Mock Object Frameworks”
  • 17.
    Stubs – Why?Separationof concernsController doesn’t depend on modelModels don’t depend on each otherEach model can be tested in isolationDon’t need the database for testingFaster testsCould use stubs to simulate a network or web service response
  • 18.
    Stubs – ImplicationsNeedto have integration testsAll of your tests could pass, but the site may not functionWebrat (used by Cucumber) & Capybara are two such integration tools
  • 19.
    MocksJust like Stubs,but with an expectation to be (or not to be) calledTest will fail if the mock is (or isn’t) calledUsed in the same way as stubs
  • 20.
    RSpec - ViewsVerifythe presence of fields on the viewAvoid relying on the layout of the viewView could break from a design changeBut good for testing groups of elements with a common purpose (like options fields that expand or hide)Use XPath or CSS selectors to locate tagsStrongly recommend CSS selectors
  • 21.
  • 22.
    RSpec - ViewsDescribecontains view pathOptional but usefulIf ‘render’ doesn’t contain arguments, use the comment on the describe line
  • 23.
    Test Coveragercov gemwill show you how much of your code has been testedrake spec:rcovBy default, all tests are runNeed to modify Rakefile to cover only specific areas like models & viewsOutput is in the <project>/coverage directoryHTML viewable in a browserOpen coverage/index.html
  • 24.
  • 25.
    RCov - TipsNoneed to try for 100% test coverageGood goal would be around 70 – 80%
  • 26.
    Automatic TestingAutotest monitorschanges to files in your projectEvery time a test is saved, the test is re-runEverytime app code is saved, corresponding test is rungem install autotest & autotest-rails-pureCreate an autotest directorydiscover.rb
  • 27.
    Autotest – TipsBecareful when using on a laptopAutotest polls for changesYou’ll either get burnt by a hot laptop or your battery will die, whichever comes firstOn OS X, you can install autotest-fsevent, the file system change triggers autotest executionGrowl notificationsautotest-growlAdd to rails root .autotest file