The Basic of RSpec 2
Authors: Triet Le – Truc Nguyen
Agenda
•TDD, BDD intro
•RSpec intro
•Expectation - Matcher
•Mocking-Stubing
•RSpec Rails
•Controller Specs
•Model Specs
•Rspec vs Cucumber
•Feature Specs
•Code coverage tool: SimpleCov, Rcov
•Example Code
Test Driven Development
Source: http://centricconsulting.com/agile-test-driven-development/
•It's 'tests' that 'drive' the 'development'
•Make sure that No code goes into production
without associated tests
•Benefits of TDD:
http://agilepainrelief.com/notesfromatooluser/2
008/10/advantages-of-tdd.html
TDD
Behavior Driven Development
BDD
•BDD is based on TDD
•BDD is specifying how your application should
work, rather than verifying that it works.
•Behaviour-Driven Development is about
implementing an application by describing its
behavior from the perspective of its
stakeholders. (Rspec book)
RSpec?
RSpec
•Rspec is unit-testing framework for Ruby
programming language
•RSpec is BDD
•Rspec's strongly recommended with TDD
How
describe `Class` do
before do
# Setup something
end
it “should return something“ do
# actual_result.should matcher(expected_result)
end
end
HOW
An Example
E
x
a
m
p
l
e
g
r
o
u
p
This is a Spec file
Expectation - Matcher
http://rubydoc.info/gems/rspec-expectations/
frames
Expectation - Matcher
•Basic structure of an rspec expectation
o Old syntax
 actual.should matcher(expected)
 actual.should_not matcher(expected)
o New
 expect(actual).to eq(expected)
 expect(actual).not_to eq(expected)
•For example
o 5.should eq(5) / expect(5).to eq(5)
o 5.should_not eq(4) / expect(5).not_to eq(5)
For Example:
Mocking - Stubbing
http://rubydoc.info/gems/rspec-mocks/frames
Mocking - Stubbing
Rspec-mocks is a test-double framework for
rspec with support for methods
o mock a `fake` object
o stubs
o message expectations on generated test-doubles and
real objects alike.
Mocking - Stubbing
•Test double
o book = double("book")
•Method Stubs
o book.stub(:title) { "The RSpec Book" }
o book.stub(:title => "The RSpec Book")
o book.stub(:title).and_return("The RSpec Book")
•Message expectations
o person = double("person")
o Person.should_receive(:find) { person }
•should_receive vs stub
Mocking - Stubbing
•Good for
o Speed up testing
o Real object is unavailable
o Difficult to access from a test environment: External
services
o Queries with complicated data setup
Mocking - Stubbing
•Problems
o Simulated API gets out of sync with actual API
o Leads to testing implementation, not effect
o Demands on integration and exploratory testing higher
with mocks
o Less value per line of test code!
RSpec-Rails
https://www.relishapp.com/rspec/rspec-rails/docs
Rspec-rails
•Add to Gemfile
•group :test, :development do
gem "rspec-rails", "~> 2.4"end
•Recommended
oFactory-girl
oGuard-spec
oSpork
o SimpleCov
Rspec-rails
source: http://www.rubyfocus.biz/
Views
Controller Routes
Application, Browser UI
Application, Server
Helpers
Model
Selenium
RSpec Integration/Request,
Cucumber, Webrat, Capybara
RSpec Views RSpec Helpers
RSpec
Controller
RSpec Routing
RSpec Model Test::Unit
Test::Unit
Functional
Test::Unit
Integration
Application, Browser UI
Application, Server
https://www.relishapp.com/rspec/rspec-rails/
v/2-13/docs/controller-specs
Controller Specs
Controller specs
•Simulate a single HTTP verb in each example
o GET
o POST
o PUT
o DELETE
o XHR
•Accessable variables
o controller, request, response
o assigns, cookies, flash, and session
Controller specs
•Check rendering
oCorrect template
 response.should render_template
oRedirect
 response.should redirect_to (url or hash)
o Status code
 response.code.should eq(200)
•Verify variable assignments
o Instance variables assigned in the controller to be
shared with the view
o Cookies sent back with the response
 cookies['key']
 cookies['key']
What need to test in model?
Model Specs
Model specs
•Exists attributes
•Association
•Model’s validations
•Class methods
•Instance methods
Model specs
For detail, a model spec should include:
•Attributes
o model attributes should have
•Association
o model association should have
•The model’s create method -> check the
validation work?
o passed valid attributes => should be valid.
o fail validations => should not be valid.
•Class and instance methods perform as
expected
Model specs - Example code
code example
Model specs - Example rspec model
code
fields, association,
validations
The model’s method create
class and
instance method
Same and difference
Rspec vs Cucumber
Rspec vs Cucumber
•Both testing frameworks.
•Both are used for Acceptance Testing
•These are business-case driven Integration
Tests
o simulate the way a user uses the application,
o the way the different parts of your application work
together can be found in a way that unit testing will not
find.
same
Rspec vs Cucumber
•RSpec and Cucumber are the business
readability factor
difference
CU CU M B ER
odraw is that the
specification (features)
from the test code
oproduct owners can
provide or review without
having to dig through code
R SPEC
odescribe a step with a
Describe, Context or It
block that contains the
business specification
oa little easier for
developers to work
obut a little harder for
non-technical folks
Example
Integration test with rspec and capybara
(and Senelium)
Feature Specs
•Introduce
•Setup env
•Example code
Feature Specs - Introduce
•high-level tests meant to exercise slices of
functionality through an application. Drive the
application only via its external interface,
usually web pages.
•Require the capybara gem, version 2.0.0 or
later. Refer to the capybara API for more infos
on the methods and matchers
•Feature, scenario, background,
given DSL <=>describe, it, before
each, let. Alias methods that allow to read
more as customer tests and acceptance tests.
Feature Specs - Setup env
First, add Capybara to your
Gemfile:
In spec/spec_helper.rb,
add two require calls for
Capybara near the top
Capybara’s DSL will be
available spec/requests
and spec/integration
directory
Feature Specs - Selenium
First, add Capybara to your
Gemfile:
In spec/spec_helper.rb,
add two require calls for
Capybara near the top
•Run Selenium, just set :js => true
Firefox should
automatically
fire up and run
with Selenium.
•Capybara.default_driver = :selenium (make
Capybara to all your tests - don’t recommend)
•Using Rack::Test (default driver) and Selenium
(JS driver) by setting the :js attribute (faster if use
Selenium for tests that actually require JS)
Feature Specs - Sample code
When writing integration tests, try to model the test around an actor (user of the system) and
the action they are performing.
Feature Specs - Sample code
code coverage tool
SimpleCov, Rcov
Demo
•Model spec
•Feature specs
Thank You!
•New syntax expectation rspec
•Feature specs
•Rspec vs cucumber
•http://www.slideshare.net/NasceniaIT/tdd-bdd-r-spec
•Intergartion test
•Setup capypara
•Devise with rspec
References

Basic RSpec 2

  • 1.
    The Basic ofRSpec 2 Authors: Triet Le – Truc Nguyen
  • 2.
    Agenda •TDD, BDD intro •RSpecintro •Expectation - Matcher •Mocking-Stubing •RSpec Rails •Controller Specs •Model Specs •Rspec vs Cucumber •Feature Specs •Code coverage tool: SimpleCov, Rcov •Example Code
  • 3.
  • 4.
  • 5.
    •It's 'tests' that'drive' the 'development' •Make sure that No code goes into production without associated tests •Benefits of TDD: http://agilepainrelief.com/notesfromatooluser/2 008/10/advantages-of-tdd.html TDD
  • 6.
  • 7.
    BDD •BDD is basedon TDD •BDD is specifying how your application should work, rather than verifying that it works. •Behaviour-Driven Development is about implementing an application by describing its behavior from the perspective of its stakeholders. (Rspec book)
  • 8.
  • 9.
    RSpec •Rspec is unit-testingframework for Ruby programming language •RSpec is BDD •Rspec's strongly recommended with TDD
  • 10.
  • 11.
    describe `Class` do beforedo # Setup something end it “should return something“ do # actual_result.should matcher(expected_result) end end HOW An Example E x a m p l e g r o u p This is a Spec file
  • 12.
  • 13.
    Expectation - Matcher •Basicstructure of an rspec expectation o Old syntax  actual.should matcher(expected)  actual.should_not matcher(expected) o New  expect(actual).to eq(expected)  expect(actual).not_to eq(expected) •For example o 5.should eq(5) / expect(5).to eq(5) o 5.should_not eq(4) / expect(5).not_to eq(5)
  • 14.
  • 15.
  • 16.
    Mocking - Stubbing Rspec-mocksis a test-double framework for rspec with support for methods o mock a `fake` object o stubs o message expectations on generated test-doubles and real objects alike.
  • 17.
    Mocking - Stubbing •Testdouble o book = double("book") •Method Stubs o book.stub(:title) { "The RSpec Book" } o book.stub(:title => "The RSpec Book") o book.stub(:title).and_return("The RSpec Book") •Message expectations o person = double("person") o Person.should_receive(:find) { person } •should_receive vs stub
  • 18.
    Mocking - Stubbing •Goodfor o Speed up testing o Real object is unavailable o Difficult to access from a test environment: External services o Queries with complicated data setup
  • 19.
    Mocking - Stubbing •Problems oSimulated API gets out of sync with actual API o Leads to testing implementation, not effect o Demands on integration and exploratory testing higher with mocks o Less value per line of test code!
  • 20.
  • 21.
    Rspec-rails •Add to Gemfile •group:test, :development do gem "rspec-rails", "~> 2.4"end •Recommended oFactory-girl oGuard-spec oSpork o SimpleCov
  • 22.
    Rspec-rails source: http://www.rubyfocus.biz/ Views Controller Routes Application,Browser UI Application, Server Helpers Model Selenium RSpec Integration/Request, Cucumber, Webrat, Capybara RSpec Views RSpec Helpers RSpec Controller RSpec Routing RSpec Model Test::Unit Test::Unit Functional Test::Unit Integration Application, Browser UI Application, Server
  • 23.
  • 24.
    Controller specs •Simulate asingle HTTP verb in each example o GET o POST o PUT o DELETE o XHR •Accessable variables o controller, request, response o assigns, cookies, flash, and session
  • 25.
    Controller specs •Check rendering oCorrecttemplate  response.should render_template oRedirect  response.should redirect_to (url or hash) o Status code  response.code.should eq(200) •Verify variable assignments o Instance variables assigned in the controller to be shared with the view o Cookies sent back with the response  cookies['key']  cookies['key']
  • 27.
    What need totest in model? Model Specs
  • 28.
    Model specs •Exists attributes •Association •Model’svalidations •Class methods •Instance methods
  • 29.
    Model specs For detail,a model spec should include: •Attributes o model attributes should have •Association o model association should have •The model’s create method -> check the validation work? o passed valid attributes => should be valid. o fail validations => should not be valid. •Class and instance methods perform as expected
  • 30.
    Model specs -Example code
  • 31.
  • 32.
    Model specs -Example rspec model code
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
    Rspec vs Cucumber •Bothtesting frameworks. •Both are used for Acceptance Testing •These are business-case driven Integration Tests o simulate the way a user uses the application, o the way the different parts of your application work together can be found in a way that unit testing will not find. same
  • 38.
    Rspec vs Cucumber •RSpecand Cucumber are the business readability factor difference CU CU M B ER odraw is that the specification (features) from the test code oproduct owners can provide or review without having to dig through code R SPEC odescribe a step with a Describe, Context or It block that contains the business specification oa little easier for developers to work obut a little harder for non-technical folks
  • 39.
  • 40.
    Integration test withrspec and capybara (and Senelium) Feature Specs •Introduce •Setup env •Example code
  • 41.
    Feature Specs -Introduce •high-level tests meant to exercise slices of functionality through an application. Drive the application only via its external interface, usually web pages. •Require the capybara gem, version 2.0.0 or later. Refer to the capybara API for more infos on the methods and matchers •Feature, scenario, background, given DSL <=>describe, it, before each, let. Alias methods that allow to read more as customer tests and acceptance tests.
  • 42.
    Feature Specs -Setup env First, add Capybara to your Gemfile: In spec/spec_helper.rb, add two require calls for Capybara near the top Capybara’s DSL will be available spec/requests and spec/integration directory
  • 43.
    Feature Specs -Selenium First, add Capybara to your Gemfile: In spec/spec_helper.rb, add two require calls for Capybara near the top •Run Selenium, just set :js => true Firefox should automatically fire up and run with Selenium. •Capybara.default_driver = :selenium (make Capybara to all your tests - don’t recommend) •Using Rack::Test (default driver) and Selenium (JS driver) by setting the :js attribute (faster if use Selenium for tests that actually require JS)
  • 44.
    Feature Specs -Sample code When writing integration tests, try to model the test around an actor (user of the system) and the action they are performing.
  • 45.
    Feature Specs -Sample code
  • 46.
  • 47.
  • 48.
  • 49.
    •New syntax expectationrspec •Feature specs •Rspec vs cucumber •http://www.slideshare.net/NasceniaIT/tdd-bdd-r-spec •Intergartion test •Setup capypara •Devise with rspec References