SlideShare a Scribd company logo
1 of 21
Download to read offline
RSpec
     documentation

http://relishapp.com/rspec
components
   RSpec Core

RSpec Expectations

  RSpec Mocks

   RSpec Rails
run specs
rake spec

rake spec:models

rspec spec/models/order_spec.rb
rspec spec/models/order_spec.rb:19
"be" matchers
describe 0 do
  it { subject.zero?.should == true }

  # vs.

  it { should be_zero } # 0.zero? == true
end
have(n).items matcher
collection.should have(x).items
collection.should have_at_least(x).items
collection.should have_at_most(x).items

it { should have(5).line_items }
subject
implicit subject
describe Comment do
  subject { Comment.new }
end
explicit subject
describe Order do
  subject { Factory.build(:order) }
end
implicit receiver
it { subject.should be_valid }

# vs.

it { should be_valid }
its
its(:status_name) { should == :draft }

its('line_items.count') { should == 5 }
let
before do
  @order = Factory.create(:shipped_order)
end

# vs.

let(:order) do
  Factory.create(:shipped_order)
end
context vs. describe
   alias :context :describe

   describe is for methods

   context is for contexts
class & instance methods
describe '#title' do # instance method
  ...
end

describe '.title' do # class method
  ...
end
context
context 'when quantity is negative' do
  before { subject.quantity = -1 }

  ...

end
model validations
it { should be_invalid }

its(:errors) { should be_present }
it { should have(1).errors_on(:quantity) }
shoulda-matchers
it 'should validate email and quantity' do
  subject.email = 'test@example.com'
  subject.quantity = -1
  subject.valid?
  should have(:no).errors_on(:email)
  should have_at_least(1).error_on(:quantity)
end

# vs.
it { should allow_value('test@example.com').for(:email) }

it { should_not allow_value(-1).for(:quantity) }
mocks
fake objects and methods

  don't touch database

      faster specs
rails model mocks
mock_model is a test double that acts like an
              ActiveModel

     stub_model is a instance of a real
 ActiveModel with some methods stubbed
using mocks
let(:email_template) do
  stub_model(EmailTemplate,
             :name => 'test_email', ...)
end

before do
  ...
  EmailTemplate.stub(:find_by_name).
    with('test_email').
    and_return(email_template)
end
message expectation
def should_deliver_mail(method)
  Mailer.should_receive(method).
    with(subject).
    and_return(double(:deliver => nil))
end
questions?

More Related Content

What's hot

Les06 (using subqueries to solve queries)
Les06 (using subqueries to solve queries)Les06 (using subqueries to solve queries)
Les06 (using subqueries to solve queries)Achmad Solichin
 
Immutability and pure functions
Immutability and pure functionsImmutability and pure functions
Immutability and pure functionssparkfabrik
 
Cold fusion best practice
Cold fusion best practiceCold fusion best practice
Cold fusion best practiceisummation
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
What's new in c# 6.0
What's new in c# 6.0What's new in c# 6.0
What's new in c# 6.0LearningTech
 
Mutability for good not evil
Mutability for good not evilMutability for good not evil
Mutability for good not evilNick Sarbicki
 
Behaviour-Driven Development
Behaviour-Driven DevelopmentBehaviour-Driven Development
Behaviour-Driven DevelopmentKerry Buckley
 
How to handle Dynamic Objects with OpKey?
How to handle Dynamic Objects with OpKey?How to handle Dynamic Objects with OpKey?
How to handle Dynamic Objects with OpKey?opkey
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteRavi Bhadauria
 
Angularjs Anti-patterns
Angularjs Anti-patternsAngularjs Anti-patterns
Angularjs Anti-patternsSteven Lambert
 
Top 10 Mistakes AngularJS Developers Make
Top 10 Mistakes AngularJS Developers MakeTop 10 Mistakes AngularJS Developers Make
Top 10 Mistakes AngularJS Developers MakeMark Meyer
 
Pretenders talk at PyconUK 2012
Pretenders talk at PyconUK 2012Pretenders talk at PyconUK 2012
Pretenders talk at PyconUK 2012txels
 

What's hot (20)

Les06 (using subqueries to solve queries)
Les06 (using subqueries to solve queries)Les06 (using subqueries to solve queries)
Les06 (using subqueries to solve queries)
 
Immutability and pure functions
Immutability and pure functionsImmutability and pure functions
Immutability and pure functions
 
Cold fusion best practice
Cold fusion best practiceCold fusion best practice
Cold fusion best practice
 
JavaScript Operators
JavaScript OperatorsJavaScript Operators
JavaScript Operators
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Books
BooksBooks
Books
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
What's new in c# 6.0
What's new in c# 6.0What's new in c# 6.0
What's new in c# 6.0
 
Mutability for good not evil
Mutability for good not evilMutability for good not evil
Mutability for good not evil
 
Lecture4
Lecture4Lecture4
Lecture4
 
Les06
Les06Les06
Les06
 
JavaScript operators
JavaScript operatorsJavaScript operators
JavaScript operators
 
Timedobserver
TimedobserverTimedobserver
Timedobserver
 
Behaviour-Driven Development
Behaviour-Driven DevelopmentBehaviour-Driven Development
Behaviour-Driven Development
 
How to handle Dynamic Objects with OpKey?
How to handle Dynamic Objects with OpKey?How to handle Dynamic Objects with OpKey?
How to handle Dynamic Objects with OpKey?
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
 
codeigniter
codeignitercodeigniter
codeigniter
 
Angularjs Anti-patterns
Angularjs Anti-patternsAngularjs Anti-patterns
Angularjs Anti-patterns
 
Top 10 Mistakes AngularJS Developers Make
Top 10 Mistakes AngularJS Developers MakeTop 10 Mistakes AngularJS Developers Make
Top 10 Mistakes AngularJS Developers Make
 
Pretenders talk at PyconUK 2012
Pretenders talk at PyconUK 2012Pretenders talk at PyconUK 2012
Pretenders talk at PyconUK 2012
 

Viewers also liked

Михаил Юматов: SaltStack
Михаил Юматов: SaltStackМихаил Юматов: SaltStack
Михаил Юматов: SaltStackit-people
 
К. Шатров "Фреймворк Capistrano", DUMP-2014
К. Шатров "Фреймворк Capistrano", DUMP-2014К. Шатров "Фреймворк Capistrano", DUMP-2014
К. Шатров "Фреймворк Capistrano", DUMP-2014it-people
 
«​Масштабируемый DevOps​» Александр Колесень
«​Масштабируемый DevOps​» Александр Колесень«​Масштабируемый DevOps​» Александр Колесень
«​Масштабируемый DevOps​» Александр КолесеньIT Share
 
"Ошибки венчурного инвестора" Леонид Волков, Бизнес-ангел
"Ошибки венчурного инвестора" Леонид Волков, Бизнес-ангел"Ошибки венчурного инвестора" Леонид Волков, Бизнес-ангел
"Ошибки венчурного инвестора" Леонид Волков, Бизнес-ангелit-people
 
Релиз инжиниринг Mail.ru, взгляд изнутри / Максим Глеков (Mail.Ru Group)
Релиз инжиниринг Mail.ru, взгляд изнутри / Максим Глеков (Mail.Ru Group)Релиз инжиниринг Mail.ru, взгляд изнутри / Максим Глеков (Mail.Ru Group)
Релиз инжиниринг Mail.ru, взгляд изнутри / Максим Глеков (Mail.Ru Group)Ontico
 
Общая концепция системы развёртывания серверного окружения на базе SaltStack ...
Общая концепция системы развёртывания серверного окружения на базе SaltStack ...Общая концепция системы развёртывания серверного окружения на базе SaltStack ...
Общая концепция системы развёртывания серверного окружения на базе SaltStack ...Positive Hack Days
 

Viewers also liked (8)

Михаил Юматов: SaltStack
Михаил Юматов: SaltStackМихаил Юматов: SaltStack
Михаил Юматов: SaltStack
 
К. Шатров "Фреймворк Capistrano", DUMP-2014
К. Шатров "Фреймворк Capistrano", DUMP-2014К. Шатров "Фреймворк Capistrano", DUMP-2014
К. Шатров "Фреймворк Capistrano", DUMP-2014
 
«​Масштабируемый DevOps​» Александр Колесень
«​Масштабируемый DevOps​» Александр Колесень«​Масштабируемый DevOps​» Александр Колесень
«​Масштабируемый DevOps​» Александр Колесень
 
Capistrano Overview
Capistrano OverviewCapistrano Overview
Capistrano Overview
 
2ª Parte Ingl BáSico Ok
2ª Parte Ingl BáSico Ok2ª Parte Ingl BáSico Ok
2ª Parte Ingl BáSico Ok
 
"Ошибки венчурного инвестора" Леонид Волков, Бизнес-ангел
"Ошибки венчурного инвестора" Леонид Волков, Бизнес-ангел"Ошибки венчурного инвестора" Леонид Волков, Бизнес-ангел
"Ошибки венчурного инвестора" Леонид Волков, Бизнес-ангел
 
Релиз инжиниринг Mail.ru, взгляд изнутри / Максим Глеков (Mail.Ru Group)
Релиз инжиниринг Mail.ru, взгляд изнутри / Максим Глеков (Mail.Ru Group)Релиз инжиниринг Mail.ru, взгляд изнутри / Максим Глеков (Mail.Ru Group)
Релиз инжиниринг Mail.ru, взгляд изнутри / Максим Глеков (Mail.Ru Group)
 
Общая концепция системы развёртывания серверного окружения на базе SaltStack ...
Общая концепция системы развёртывания серверного окружения на базе SaltStack ...Общая концепция системы развёртывания серверного окружения на базе SaltStack ...
Общая концепция системы развёртывания серверного окружения на базе SaltStack ...
 

Similar to Rspec

Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsUses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsPatchSpace Ltd
 
Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Vysakh Sreenivasan
 
Антипаттерны модульного тестирования
Антипаттерны модульного тестированияАнтипаттерны модульного тестирования
Антипаттерны модульного тестированияMitinPavel
 
Tips to make your rspec specs awesome
Tips to make your rspec specs awesomeTips to make your rspec specs awesome
Tips to make your rspec specs awesomeSwati Jadhav
 
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and JasmineRails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and JasmineRaimonds Simanovskis
 
RSpec 3: The new, the old, the good
RSpec 3: The new, the old, the goodRSpec 3: The new, the old, the good
RSpec 3: The new, the old, the goodmglrnm
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescriptDavid Furber
 
Scala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love GameScala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love GameAntony Stubbs
 
Ruby on Rails testing with Rspec
Ruby on Rails testing with RspecRuby on Rails testing with Rspec
Ruby on Rails testing with RspecBunlong Van
 
JavaScript / Web Engineering / Web Development / html + css + js/presentation
JavaScript / Web Engineering / Web Development / html + css + js/presentationJavaScript / Web Engineering / Web Development / html + css + js/presentation
JavaScript / Web Engineering / Web Development / html + css + js/presentationM Sajid R
 
Objectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxObjectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxdunhamadell
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)BoneyGawande
 
A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyVysakh Sreenivasan
 
ObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docxObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docxvannagoforth
 
Write codeforhumans
Write codeforhumansWrite codeforhumans
Write codeforhumansNarendran R
 

Similar to Rspec (20)

Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsUses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & Stubs
 
Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)
 
Антипаттерны модульного тестирования
Антипаттерны модульного тестированияАнтипаттерны модульного тестирования
Антипаттерны модульного тестирования
 
Tips to make your rspec specs awesome
Tips to make your rspec specs awesomeTips to make your rspec specs awesome
Tips to make your rspec specs awesome
 
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and JasmineRails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
RSpec 3: The new, the old, the good
RSpec 3: The new, the old, the goodRSpec 3: The new, the old, the good
RSpec 3: The new, the old, the good
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
Rspec
RspecRspec
Rspec
 
Scala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love GameScala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love Game
 
Ruby on Rails testing with Rspec
Ruby on Rails testing with RspecRuby on Rails testing with Rspec
Ruby on Rails testing with Rspec
 
JavaScript / Web Engineering / Web Development / html + css + js/presentation
JavaScript / Web Engineering / Web Development / html + css + js/presentationJavaScript / Web Engineering / Web Development / html + css + js/presentation
JavaScript / Web Engineering / Web Development / html + css + js/presentation
 
Specs2
Specs2Specs2
Specs2
 
Objectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxObjectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docx
 
Rails on Oracle 2011
Rails on Oracle 2011Rails on Oracle 2011
Rails on Oracle 2011
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced Ruby
 
ObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docxObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docx
 
Write codeforhumans
Write codeforhumansWrite codeforhumans
Write codeforhumans
 

Rspec