SlideShare a Scribd company logo
SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY
Lecture 5
RSpec testing,
SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY
Automated testing
Testing is a checking if your code is right
Every developer actually checks his project for
outputting correct values for different values.
Since testing is done many times and many
operations are repeated over a time, it is needed to
be automated
SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY
TDD - Test Driven
Development
Development where you first write tests and then
write code for them.
It is good for following cases:
Developers better understand what to do
It can be used as documentation
RSpec on Rails
(Engineering Software as a Service §8.2)
Armando Fox
© 2012 Armando Fox & David Patterson
Licensed under Creative Commons Attribution-
NonCommercial-ShareAlike 3.0 Unported
License
SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY
RSpec
RSpec is a library to do automatic testing
SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY
RSpec usage
It’s tests are inside spec folder
To use in project: write in Gemfile
gem 'rspec-rails'
rails generate rspec:install
run rake db:migrate
then run rake db:test:prepare
Last command prepares test database for testing
then run rspec
RSpec, a Domain-Specific
Language for testing
• RSpec tests (specs) inhabit spec directory
rails generate rspec:install creates
structure
• Unit tests (model, helpers)
• Functional tests (controllers)
• Integration tests (views)?
app/models/*.rb spec/models/*_spec.rb
app/controllers/
*_controller.rb
spec/controllers/
*_controller_spec.rb
app/views/*/*.html.haml (use Cucumber!)
The TDD Cycle:
Red–Green–Refactor
(Engineering Software as a Service §8.3)
Armando Fox
© 2013 Armando Fox & David Patterson, all rights reserved
Test-First development
• Think about one thing the code should do
• Capture that thought in a test, which fails
• Write the simplest possible code that lets the
test pass
• Refactor: DRY out commonality w/other tests
• Continue with next thing code should do
Red – Green – Refactor
Aim for “always have working code”
How to test something “in
isolation” if it has dependencies
that would affect test?
The Code You Wish You Had
What should the controller method do that
receives the search form?
1.it should call a method that will search
TMDb for specified movie
2.if match found: it should select (new)
“Search Results” view to display match
3.If no match found: it should redirect to RP
home page with message
TDD for the Controller action:
Setup
• Add a route to config/routes.rb
# Route that posts 'Search TMDb' form
post '/movies/search_tmdb'
– Convention over configuration will map this to
MoviesController#search_tmdb
• Create an empty view:
touch app/views/movies/search_tmdb.html.haml
• Replace fake “hardwired” method in
movies_controller.rb with empty method:
def search_tmdb
end
What model method?
• Calling TMDb is responsibility of the model... but
no model method exists to do this yet!
• No problem...we’ll use a seam to test the code we
wish we had (“CWWWH”), Movie.find_in_tmdb
• Game plan:
– Simulate POSTing search form to controller action.
– Check that controller action tries to call Movie.find_in_tmdb
with data from submitted form.
– The test will fail (red), because the (empty) controller
method doesn’t call find_in_tmdb.
– Fix controller action to make green.
http://pastebin.com/zKnw
phQZ
Optional!
Test techniques we know
obj.should_receive(a).with(b)
Should & Should-not
• Matcher applies test to receiver of should
count.should == 5` Syntactic sugar for
count.should.==(5)
5.should(be.<(7)) be creates a lambda that tests the
predicate expression
5.should be < 7 Syntactic sugar allowed
5.should be_odd Use method_missing to call odd?
on 5
result.should include(elt) calls #include?, which usually gets
handled by Enumerable
republican.should
cooperate_with(democrat)
calls programmer’s custom
matcher #cooperate_with (and
probably fails)
result.should render_template('search_tmdb')
SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY
spec/model/person_spec.rb
This file tests model Person, the line starting with it
is one test, text next to it is name of test, inside
function
require ‘spec_helper’
describe Person do
it ‘is invalid without name’ do
Person.create.should_not be_valid
end
end
SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY
should
should or should_not are next to object you want to
test
after should or should_not you can write:
== equals
be_valid if model is valid
have_text
redirect_to
http://rspec.rubyforge.org/rspec-rails/1.1.12/classes/Spec/Rails/Matchers.html
SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY
Associations
basic
SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY
Problem
We have two tables: Students and Group
Each group contains many students, so in students
table it has foreign key to group table.
So table students: name, surname, group_id
and table group: title
SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY
Dumb way #1:
Creating model and migrating
rails generate model Group title:string
rails generate model Student name:string
surname:string group_id:integer
rake db:migrate
SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY
Dumb way #1:
show all students of group #1
gr = Group.find(1)
studs = Student.all.where(group_id: gr.id)
This code is not beautiful, because it would be
better to find all students of group from object
SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY
has_many and belongs
add line has_many :students to Group model
and line belongs_to :group to Student model
Note: has_many is in plural form and belongs_to in
singular form
Now you can use:
gr = Group.find(1)
gr.students
Which will show all students of group with id 1
SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY
How it works
When you add belongs_to field to Student model, it
understands that foreign_key should be called
group_id, and works with it
SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY
Simplifying
Instead of
rails generate model Student name:string group_id:integer
it’s better to use
rails generate model Student name:string group:references
Two commands create same database tables, but
second command automatically adds belongs_to
to Student table
SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY
Working through associations
grr = Group.find(1)
grr.students.create(:name=>”John”)
grr.students<<Student.create(:name=>”John”)
grr.students[2].name
SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY
has_one with different name
has_one :capital, :class_name=>”City”, foreign_key=>”capital_id”

More Related Content

What's hot

Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif IqbalCode Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Cefalo
 
Agile korea 2013 유석문
Agile korea 2013 유석문Agile korea 2013 유석문
Agile korea 2013 유석문
Sangcheol Hwang
 
Refactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeRefactoring: Improve the design of existing code
Refactoring: Improve the design of existing code
Valerio Maggio
 
ABAPCodeRetreat - TDD Intro by Damir Majer
ABAPCodeRetreat - TDD Intro by Damir MajerABAPCodeRetreat - TDD Intro by Damir Majer
ABAPCodeRetreat - TDD Intro by Damir Majer
ABAPCodeRetreat
 
Test Driven Development #sitFRA
Test Driven Development #sitFRATest Driven Development #sitFRA
Test Driven Development #sitFRA
Christian Drumm
 
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven DevelopmentABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
Hendrik Neumann
 
Refactoring
RefactoringRefactoring
Refactoring
AngelLuisBlasco
 
Chapter17 of clean code
Chapter17 of clean codeChapter17 of clean code
Chapter17 of clean code
Kuyseng Chhoeun
 
TDD - survival guide
TDD - survival guide TDD - survival guide
TDD - survival guide
vitalipe
 
Refactoring: Code it Clean
Refactoring: Code it CleanRefactoring: Code it Clean
Refactoring: Code it Clean
AliGermiyanoglu
 
Testing GraphQL in Your JavaScript Application: From Zero to Hundred Percent
Testing GraphQL in Your JavaScript Application: From Zero to Hundred PercentTesting GraphQL in Your JavaScript Application: From Zero to Hundred Percent
Testing GraphQL in Your JavaScript Application: From Zero to Hundred Percent
Roy Derks
 
Refactoring 101
Refactoring 101Refactoring 101
Refactoring 101
Adam Culp
 
Clean code
Clean codeClean code
Clean code
NadiiaVlasenko
 
TDD, BDD and mocks
TDD, BDD and mocksTDD, BDD and mocks
TDD, BDD and mocks
Kerry Buckley
 
Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기
Myeongseok Baek
 
PramodMishra_Profile
PramodMishra_ProfilePramodMishra_Profile
PramodMishra_Profile
Pramod Mishra
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review Process
Dr. Syed Hassan Amin
 
TDD & BDD
TDD & BDDTDD & BDD
TDD & BDD
Arvind Vyas
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
Maris Prabhakaran M
 
.Net Debugging Techniques
.Net Debugging Techniques.Net Debugging Techniques
.Net Debugging Techniques
Bala Subra
 

What's hot (20)

Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif IqbalCode Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
 
Agile korea 2013 유석문
Agile korea 2013 유석문Agile korea 2013 유석문
Agile korea 2013 유석문
 
Refactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeRefactoring: Improve the design of existing code
Refactoring: Improve the design of existing code
 
ABAPCodeRetreat - TDD Intro by Damir Majer
ABAPCodeRetreat - TDD Intro by Damir MajerABAPCodeRetreat - TDD Intro by Damir Majer
ABAPCodeRetreat - TDD Intro by Damir Majer
 
Test Driven Development #sitFRA
Test Driven Development #sitFRATest Driven Development #sitFRA
Test Driven Development #sitFRA
 
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven DevelopmentABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
 
Refactoring
RefactoringRefactoring
Refactoring
 
Chapter17 of clean code
Chapter17 of clean codeChapter17 of clean code
Chapter17 of clean code
 
TDD - survival guide
TDD - survival guide TDD - survival guide
TDD - survival guide
 
Refactoring: Code it Clean
Refactoring: Code it CleanRefactoring: Code it Clean
Refactoring: Code it Clean
 
Testing GraphQL in Your JavaScript Application: From Zero to Hundred Percent
Testing GraphQL in Your JavaScript Application: From Zero to Hundred PercentTesting GraphQL in Your JavaScript Application: From Zero to Hundred Percent
Testing GraphQL in Your JavaScript Application: From Zero to Hundred Percent
 
Refactoring 101
Refactoring 101Refactoring 101
Refactoring 101
 
Clean code
Clean codeClean code
Clean code
 
TDD, BDD and mocks
TDD, BDD and mocksTDD, BDD and mocks
TDD, BDD and mocks
 
Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기
 
PramodMishra_Profile
PramodMishra_ProfilePramodMishra_Profile
PramodMishra_Profile
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review Process
 
TDD & BDD
TDD & BDDTDD & BDD
TDD & BDD
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
.Net Debugging Techniques
.Net Debugging Techniques.Net Debugging Techniques
.Net Debugging Techniques
 

Similar to Web tech: lecture 5

Developers’ mDay u Banjoj Luci - Milan Popović, PHP Srbija – Testimony (about...
Developers’ mDay u Banjoj Luci - Milan Popović, PHP Srbija – Testimony (about...Developers’ mDay u Banjoj Luci - Milan Popović, PHP Srbija – Testimony (about...
Developers’ mDay u Banjoj Luci - Milan Popović, PHP Srbija – Testimony (about...
mCloud
 
Test-driven development and Umple
Test-driven development and UmpleTest-driven development and Umple
Test-driven development and Umple
tylerjdmcconnell
 
10 Ways To Improve Your Code
10 Ways To Improve Your Code10 Ways To Improve Your Code
10 Ways To Improve Your Code
ConSanFrancisco123
 
Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013
Brian Sam-Bodden
 
Survive the Chaos - S4H151 - SAP TechED Barcelona 2017 - Lecture
Survive the Chaos - S4H151 - SAP TechED Barcelona 2017 - LectureSurvive the Chaos - S4H151 - SAP TechED Barcelona 2017 - Lecture
Survive the Chaos - S4H151 - SAP TechED Barcelona 2017 - Lecture
Rainer Winkler
 
Quick Intro to Clean Coding
Quick Intro to Clean CodingQuick Intro to Clean Coding
Quick Intro to Clean Coding
Ecommerce Solution Provider SysIQ
 
Hands-on Experience Model based testing with spec explorer
Hands-on Experience Model based testing with spec explorer Hands-on Experience Model based testing with spec explorer
Hands-on Experience Model based testing with spec explorer
Rachid Kherrazi
 
Clean Code - Part 2
Clean Code - Part 2Clean Code - Part 2
Clean Code - Part 2
Knoldus Inc.
 
Software development best practices & coding guidelines
Software development best practices & coding guidelinesSoftware development best practices & coding guidelines
Software development best practices & coding guidelines
Ankur Goyal
 
10 Ways To Improve Your Code( Neal Ford)
10  Ways To  Improve  Your  Code( Neal  Ford)10  Ways To  Improve  Your  Code( Neal  Ford)
10 Ways To Improve Your Code( Neal Ford)
guestebde
 
Testing practicies not only in scala
Testing practicies not only in scalaTesting practicies not only in scala
Testing practicies not only in scala
Paweł Panasewicz
 
Rachid kherrazi-testing-asd-interface-compliance-with-asd spec
Rachid kherrazi-testing-asd-interface-compliance-with-asd specRachid kherrazi-testing-asd-interface-compliance-with-asd spec
Rachid kherrazi-testing-asd-interface-compliance-with-asd spec
Rachid Kherrazi
 
Ian Cooper webinar for DDD Iran: Kent beck style tdd seven years after
Ian Cooper webinar for DDD Iran: Kent beck style tdd   seven years afterIan Cooper webinar for DDD Iran: Kent beck style tdd   seven years after
Ian Cooper webinar for DDD Iran: Kent beck style tdd seven years after
Iranian Domain-Driven Design Community
 
Tdd is not about testing
Tdd is not about testingTdd is not about testing
Tdd is not about testing
Gianluca Padovani
 
2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop
Wolfram Arnold
 
Beginning AngularJS
Beginning AngularJSBeginning AngularJS
Beginning AngularJS
Troy Miles
 
Better java with design
Better java with designBetter java with design
Better java with design
Narayann Swaami
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
ZendCon
 
Commonly used design patterns
Commonly used design patternsCommonly used design patterns
Commonly used design patterns
Mojammel Haque
 
The Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and EverythingThe Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and Everything
Andrey Karpov
 

Similar to Web tech: lecture 5 (20)

Developers’ mDay u Banjoj Luci - Milan Popović, PHP Srbija – Testimony (about...
Developers’ mDay u Banjoj Luci - Milan Popović, PHP Srbija – Testimony (about...Developers’ mDay u Banjoj Luci - Milan Popović, PHP Srbija – Testimony (about...
Developers’ mDay u Banjoj Luci - Milan Popović, PHP Srbija – Testimony (about...
 
Test-driven development and Umple
Test-driven development and UmpleTest-driven development and Umple
Test-driven development and Umple
 
10 Ways To Improve Your Code
10 Ways To Improve Your Code10 Ways To Improve Your Code
10 Ways To Improve Your Code
 
Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013
 
Survive the Chaos - S4H151 - SAP TechED Barcelona 2017 - Lecture
Survive the Chaos - S4H151 - SAP TechED Barcelona 2017 - LectureSurvive the Chaos - S4H151 - SAP TechED Barcelona 2017 - Lecture
Survive the Chaos - S4H151 - SAP TechED Barcelona 2017 - Lecture
 
Quick Intro to Clean Coding
Quick Intro to Clean CodingQuick Intro to Clean Coding
Quick Intro to Clean Coding
 
Hands-on Experience Model based testing with spec explorer
Hands-on Experience Model based testing with spec explorer Hands-on Experience Model based testing with spec explorer
Hands-on Experience Model based testing with spec explorer
 
Clean Code - Part 2
Clean Code - Part 2Clean Code - Part 2
Clean Code - Part 2
 
Software development best practices & coding guidelines
Software development best practices & coding guidelinesSoftware development best practices & coding guidelines
Software development best practices & coding guidelines
 
10 Ways To Improve Your Code( Neal Ford)
10  Ways To  Improve  Your  Code( Neal  Ford)10  Ways To  Improve  Your  Code( Neal  Ford)
10 Ways To Improve Your Code( Neal Ford)
 
Testing practicies not only in scala
Testing practicies not only in scalaTesting practicies not only in scala
Testing practicies not only in scala
 
Rachid kherrazi-testing-asd-interface-compliance-with-asd spec
Rachid kherrazi-testing-asd-interface-compliance-with-asd specRachid kherrazi-testing-asd-interface-compliance-with-asd spec
Rachid kherrazi-testing-asd-interface-compliance-with-asd spec
 
Ian Cooper webinar for DDD Iran: Kent beck style tdd seven years after
Ian Cooper webinar for DDD Iran: Kent beck style tdd   seven years afterIan Cooper webinar for DDD Iran: Kent beck style tdd   seven years after
Ian Cooper webinar for DDD Iran: Kent beck style tdd seven years after
 
Tdd is not about testing
Tdd is not about testingTdd is not about testing
Tdd is not about testing
 
2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop
 
Beginning AngularJS
Beginning AngularJSBeginning AngularJS
Beginning AngularJS
 
Better java with design
Better java with designBetter java with design
Better java with design
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Commonly used design patterns
Commonly used design patternsCommonly used design patterns
Commonly used design patterns
 
The Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and EverythingThe Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and Everything
 

Web tech: lecture 5

  • 1. SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY Lecture 5 RSpec testing,
  • 2. SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY Automated testing Testing is a checking if your code is right Every developer actually checks his project for outputting correct values for different values. Since testing is done many times and many operations are repeated over a time, it is needed to be automated
  • 3. SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY TDD - Test Driven Development Development where you first write tests and then write code for them. It is good for following cases: Developers better understand what to do It can be used as documentation
  • 4. RSpec on Rails (Engineering Software as a Service §8.2) Armando Fox © 2012 Armando Fox & David Patterson Licensed under Creative Commons Attribution- NonCommercial-ShareAlike 3.0 Unported License
  • 5. SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY RSpec RSpec is a library to do automatic testing
  • 6. SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY RSpec usage It’s tests are inside spec folder To use in project: write in Gemfile gem 'rspec-rails' rails generate rspec:install run rake db:migrate then run rake db:test:prepare Last command prepares test database for testing then run rspec
  • 7. RSpec, a Domain-Specific Language for testing • RSpec tests (specs) inhabit spec directory rails generate rspec:install creates structure • Unit tests (model, helpers) • Functional tests (controllers) • Integration tests (views)? app/models/*.rb spec/models/*_spec.rb app/controllers/ *_controller.rb spec/controllers/ *_controller_spec.rb app/views/*/*.html.haml (use Cucumber!)
  • 8. The TDD Cycle: Red–Green–Refactor (Engineering Software as a Service §8.3) Armando Fox © 2013 Armando Fox & David Patterson, all rights reserved
  • 9. Test-First development • Think about one thing the code should do • Capture that thought in a test, which fails • Write the simplest possible code that lets the test pass • Refactor: DRY out commonality w/other tests • Continue with next thing code should do Red – Green – Refactor Aim for “always have working code”
  • 10. How to test something “in isolation” if it has dependencies that would affect test?
  • 11. The Code You Wish You Had What should the controller method do that receives the search form? 1.it should call a method that will search TMDb for specified movie 2.if match found: it should select (new) “Search Results” view to display match 3.If no match found: it should redirect to RP home page with message
  • 12. TDD for the Controller action: Setup • Add a route to config/routes.rb # Route that posts 'Search TMDb' form post '/movies/search_tmdb' – Convention over configuration will map this to MoviesController#search_tmdb • Create an empty view: touch app/views/movies/search_tmdb.html.haml • Replace fake “hardwired” method in movies_controller.rb with empty method: def search_tmdb end
  • 13. What model method? • Calling TMDb is responsibility of the model... but no model method exists to do this yet! • No problem...we’ll use a seam to test the code we wish we had (“CWWWH”), Movie.find_in_tmdb • Game plan: – Simulate POSTing search form to controller action. – Check that controller action tries to call Movie.find_in_tmdb with data from submitted form. – The test will fail (red), because the (empty) controller method doesn’t call find_in_tmdb. – Fix controller action to make green. http://pastebin.com/zKnw phQZ
  • 14. Optional! Test techniques we know obj.should_receive(a).with(b)
  • 15. Should & Should-not • Matcher applies test to receiver of should count.should == 5` Syntactic sugar for count.should.==(5) 5.should(be.<(7)) be creates a lambda that tests the predicate expression 5.should be < 7 Syntactic sugar allowed 5.should be_odd Use method_missing to call odd? on 5 result.should include(elt) calls #include?, which usually gets handled by Enumerable republican.should cooperate_with(democrat) calls programmer’s custom matcher #cooperate_with (and probably fails) result.should render_template('search_tmdb')
  • 16. SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY spec/model/person_spec.rb This file tests model Person, the line starting with it is one test, text next to it is name of test, inside function require ‘spec_helper’ describe Person do it ‘is invalid without name’ do Person.create.should_not be_valid end end
  • 17. SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY should should or should_not are next to object you want to test after should or should_not you can write: == equals be_valid if model is valid have_text redirect_to http://rspec.rubyforge.org/rspec-rails/1.1.12/classes/Spec/Rails/Matchers.html
  • 18. SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY Associations basic
  • 19. SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY Problem We have two tables: Students and Group Each group contains many students, so in students table it has foreign key to group table. So table students: name, surname, group_id and table group: title
  • 20. SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY Dumb way #1: Creating model and migrating rails generate model Group title:string rails generate model Student name:string surname:string group_id:integer rake db:migrate
  • 21. SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY Dumb way #1: show all students of group #1 gr = Group.find(1) studs = Student.all.where(group_id: gr.id) This code is not beautiful, because it would be better to find all students of group from object
  • 22. SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY has_many and belongs add line has_many :students to Group model and line belongs_to :group to Student model Note: has_many is in plural form and belongs_to in singular form Now you can use: gr = Group.find(1) gr.students Which will show all students of group with id 1
  • 23. SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY How it works When you add belongs_to field to Student model, it understands that foreign_key should be called group_id, and works with it
  • 24. SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY Simplifying Instead of rails generate model Student name:string group_id:integer it’s better to use rails generate model Student name:string group:references Two commands create same database tables, but second command automatically adds belongs_to to Student table
  • 25. SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY Working through associations grr = Group.find(1) grr.students.create(:name=>”John”) grr.students<<Student.create(:name=>”John”) grr.students[2].name
  • 26. SULEYMAN DEMIREL UNIVERSITY : ENGINEERING FACULTY : © ARDAK SHALKARBAYULY has_one with different name has_one :capital, :class_name=>”City”, foreign_key=>”capital_id”