SlideShare a Scribd company logo
v.1.0
2015.08.09
Hosang Jeon
jhsbeat@gmail.com
HOW TO TEST
IN RUBY ON RAILS
• 코드 변경의 side effect를 초기에 파악할 수 있다... 등등의 일반적인 Unit Test의 필요성

+
• Rails Way를 자연스럽게 익힐 수 있다.
• 즉, Rails Way를 따르지 않은 방식은 테스트에서 문제가 발생한다.
WHY IS UNIT TEST NECESSARY / SO IMPORTANT?
THINGS YOU SHOULD KNOW
• 대부분의 레일스 애플리케이션은 데이터베이스와의 상호작용을 통해 동작하기 때문에
테스트 역시 데이터베이스를 필요로 한다.
• 이러한 이유로 효과적인 테스트를 수행하기 위해서는 어떻게 데이터베이스를 세팅하고
샘플 데이터를 집어넣는 지에 대해서 이해할 필요가 있다.
• 테스트를 위한 데이터베이스와 개발을 위한 데이터베이스를 함께 사용하는 경우 샘플 데
이터가 개발용 데이터를 망칠 수 있기 때문에 테스트용 데이터베이스를 별도로 두는 것
이 안전하다. 두어야만 한다.
test/ 테스트 관련 파일들의 루트 디렉토리
models/ 모델관련 테스트 클래스들이 있는 디렉토리
controllers/ 컨트롤러관련 테스트 클래스들이 있는 디렉토리
integrations/ 여러개의 컨트롤러와 연관된 테스트 클래스들이 있는 디렉토리
helpers/ 헬퍼관련 테스트 클래스들이 있는 디렉토리
mailers/ 메일러관련 테스트 클래스들이 있는 디렉토리
fixtures/ 테스트 데이터들(fixture)이 들어있는 디렉토리
test_helper.rb 테스트와 관련된 기본 설정들을 담고 있는 클래스
DIRECTORIES FOR TEST IN RAILS
RAKE TASKS FOR RUNNING YOUR TEST
TASKS DESCRIPTION
rake test
Runs all tests in the test folder. You can also simply run rake as Rails will run
all the tests by default
rake test:controllers Runs all the controller tests from test/controllers
rake test:functionals
Runs all the functional tests from test/controllers, test/mailers, and
test/functional
rake test:helpers Runs all the helper tests from test/helpers
rake test:integration Runs all the integration tests from test/integration
rake test:jobs Runs all the job tests from test/jobs
rake test:mailers Runs all the mailer tests from test/mailers
rake test:models Runs all the model tests from test/models
rake test:units Runs all the unit tests from test/models, test/helpers, and test/unit
rake test:db Runs all tests in the test folder and resets the db
픽스쳐(Fixtures)란
 무엇인가?
In software testing, a test fixture is a fixed state of
the software under test used as a baseline for
running tests; also known as the test context.
https://en.wikipedia.org/wiki/Test_fixture#Software
테스트 픽서쳐란, 소프트웨어 테스트의
기준이 되는 고정된 상태값을 의미한다.
픽스쳐(Fixtures)란
 무엇인가?
• 샘플(테스트) 데이터를 멋있게 부르는 말
• YAML 로 작성되어 있음.
• 일종의 ActiveRecord object 라고 생각하면 됨
• Fixture 파일명은 테이블의 이름과 반드시 일치해야 한다.
david:
name: David Heinemeier Hansson
birthday: 1979-10-15
profession: Systems development
steve:
name: Steve Ross Kellock
birthday: 1974-09-27
# In fixtures/categories.yml
about:
name: About
# In fixtures/articles.yml
one:
title: Welcome to Rails!
body: Hello world!
category: about
픽스쳐(Fixtures)란
 무엇인가?
• 만약, fixture 안에서 association을 정의해야 하는 경우 아래와 같이 

reference node 를 지정해 주면 됨.
reference node
belongs_to
픽스쳐(Fixtures)란
 무엇인가?
• 만약, 픽스쳐파일의 확장자 끝에 .erb를 붙여주면 루비코드를 사용할 수 있다.
• 루비코드를 이용하면 많은 양의 테스트 데이터를 손쉽게 생성할 수 있다.
% 1000.times do |n| %
user_%= n %:
username: %= user#{n} %
email: %= user#{n}@example.com %
% end %
픽스쳐의
 동작방식
• Rails는 test/fixtures 하위에 있는 모든 픽스쳐들을 세 단계에 걸쳐 로딩한다.
1. 픽스쳐에 해당하는 테이블의 기존 데이터를 삭제 한다.
2. 픽스쳐 데이터를 테이블에 로드 한다.
3. 픽스쳐 데이터에 직접 접근하고자 하는 경우에는 이를 변수에 덤프 한다.
• 픽스쳐의 각 데이터는 아래와 같이 직접 접근이 가능하다.
accessed by node name
# In fixtures/users.yml
david:
name: David Heinemeier Hansson
birthday: 1979-10-15
profession: Systems development
# In test class
users(:david)
users(:david).id
UNIT
 TEST
 for
 YOUR
 MODELS
require 'test_helper'
 
class ArticleTest  ActiveSupport::TestCase
  # test the truth do
  #   assert true
  # end
end
DEFAULT
 TEST
 CASE
 generated
 by
 Rails
• Minitest::Test 를 상속한 클래스에서는 test_ 로 시작하는 모든 메서드를 자동적으
로 테스트케이스로 인식하여 테스트 수행시 자동적으로 수행하게 된다.
• Rails는 여기에 test 라는 이름의 메서드를 추가하였는데, 이 메서드는 [테스트 명]과 [블록]
을 받아서 이를 일반적인 Minitest::Unit으로 생성해 준다. 즉, 위의 코드에서 test
“the truth” do... 는 실제로 아래와 같은 메서드를 생성한다.
test_helper.rb : 모든 테스트에 공통적으로 적용되는 기본 설정을 정의하는 클래스
Minitest::Test
ActiveSupport::TestCase
ArticleTest
def test_the_truth
assert true
end
MODEL
 TEST
 IN
 ACTION
require test_helper



class ProductTest  ActiveSupport::TestCase

test product price must be positive do

product = Product.new(title: My Book Title,

description: yyy,

image_url: zzz.jpg)

product.price = -1

assert product.invalid?, negative price of a product must be invalid.

assert product.errors.has_key?(:price), an invalid product must have an error



product.price = 0

assert product.invalid?, negative price of a product must be invalid.

assert product.errors.has_key?(:price), an invalid product must have an error



product.price = 1

assert product.valid?, positive price of a product must be valid.

assert_empty product.errors, a valid product must have no error

end

end
SIMPLE
 MODEL
 TEST
 CASE
Product의 가격이 항상 0보다 커야함을 테스트. 가격이 -1, 0인 경우 모델은 invalid 해야 하고,
error가 존재해야 함.
가격이 1인 경우 모델은 valid 해야 하고, error가 nil이어야 함.
assertion의 두번재 파라미터는 해당
assertion이 실패했을 때 보여줄 메시지이다.

More Related Content

What's hot

Building Quality with Foundations of Mud
Building Quality with Foundations of MudBuilding Quality with Foundations of Mud
Building Quality with Foundations of Mudseleniumconf
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
guy_davis
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
Arulalan T
 
PL/SQL unit testing with Ruby
PL/SQL unit testing with RubyPL/SQL unit testing with Ruby
PL/SQL unit testing with Ruby
Raimonds Simanovskis
 
Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018
Justin James
 
Client side unit tests - using jasmine & karma
Client side unit tests - using jasmine & karmaClient side unit tests - using jasmine & karma
Client side unit tests - using jasmine & karma
Adam Klein
 
Refactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationRefactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test Automation
Stephen Fuqua
 
How Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiHow Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran Mizrahi
Ran Mizrahi
 
JavaFX8 TestFX - CDI
JavaFX8   TestFX - CDIJavaFX8   TestFX - CDI
JavaFX8 TestFX - CDI
Sven Ruppert
 
Angular Unit Testing from the Trenches
Angular Unit Testing from the TrenchesAngular Unit Testing from the Trenches
Angular Unit Testing from the Trenches
Justin James
 
Software testing ... who’s responsible is it?
Software testing ... who’s responsible is it?Software testing ... who’s responsible is it?
Software testing ... who’s responsible is it?
Manjula03809891
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++
Hong Le Van
 
Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.
Deepak Singhvi
 
Test
TestTest
Test
Eddie Kao
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to Mutation
Paul Blundell
 
(Unit )-Testing for Joomla
(Unit )-Testing for Joomla(Unit )-Testing for Joomla
(Unit )-Testing for Joomla
David Jardin
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's tests
Sean P. Floyd
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
alessiopace
 

What's hot (20)

Building Quality with Foundations of Mud
Building Quality with Foundations of MudBuilding Quality with Foundations of Mud
Building Quality with Foundations of Mud
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 
PL/SQL unit testing with Ruby
PL/SQL unit testing with RubyPL/SQL unit testing with Ruby
PL/SQL unit testing with Ruby
 
Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018
 
Client side unit tests - using jasmine & karma
Client side unit tests - using jasmine & karmaClient side unit tests - using jasmine & karma
Client side unit tests - using jasmine & karma
 
Refactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationRefactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test Automation
 
How Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiHow Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran Mizrahi
 
JavaFX8 TestFX - CDI
JavaFX8   TestFX - CDIJavaFX8   TestFX - CDI
JavaFX8 TestFX - CDI
 
Angular Unit Testing from the Trenches
Angular Unit Testing from the TrenchesAngular Unit Testing from the Trenches
Angular Unit Testing from the Trenches
 
Software testing ... who’s responsible is it?
Software testing ... who’s responsible is it?Software testing ... who’s responsible is it?
Software testing ... who’s responsible is it?
 
Laravel Unit Testing
Laravel Unit TestingLaravel Unit Testing
Laravel Unit Testing
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++
 
Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.
 
Test
TestTest
Test
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to Mutation
 
(Unit )-Testing for Joomla
(Unit )-Testing for Joomla(Unit )-Testing for Joomla
(Unit )-Testing for Joomla
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's tests
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
 

Viewers also liked

자동화된 Test Case의 효과
자동화된 Test Case의 효과자동화된 Test Case의 효과
자동화된 Test Case의 효과
도형 임
 
테스트 케이스와 SW 품질
테스트 케이스와 SW 품질테스트 케이스와 SW 품질
테스트 케이스와 SW 품질
도형 임
 
테스트 가능한 소프트웨어 설계와 TDD작성 패턴 (Testable design and TDD)
테스트 가능한 소프트웨어 설계와 TDD작성 패턴 (Testable design and TDD)테스트 가능한 소프트웨어 설계와 TDD작성 패턴 (Testable design and TDD)
테스트 가능한 소프트웨어 설계와 TDD작성 패턴 (Testable design and TDD)Suwon Chae
 
테스트자동화 성공전략
테스트자동화 성공전략테스트자동화 성공전략
테스트자동화 성공전략
SangIn Choung
 
[2A4]DeepLearningAtNAVER
[2A4]DeepLearningAtNAVER[2A4]DeepLearningAtNAVER
[2A4]DeepLearningAtNAVER
NAVER D2
 
Ai 그까이거
Ai 그까이거Ai 그까이거
Ai 그까이거
도형 임
 
Ui test 자동화하기 - Selenium + Jenkins
Ui test 자동화하기 - Selenium + JenkinsUi test 자동화하기 - Selenium + Jenkins
Ui test 자동화하기 - Selenium + Jenkins
Chang Hak Yeon
 
딥러닝과 강화 학습으로 나보다 잘하는 쿠키런 AI 구현하기 DEVIEW 2016
딥러닝과 강화 학습으로 나보다 잘하는 쿠키런 AI 구현하기 DEVIEW 2016딥러닝과 강화 학습으로 나보다 잘하는 쿠키런 AI 구현하기 DEVIEW 2016
딥러닝과 강화 학습으로 나보다 잘하는 쿠키런 AI 구현하기 DEVIEW 2016
Taehoon Kim
 

Viewers also liked (8)

자동화된 Test Case의 효과
자동화된 Test Case의 효과자동화된 Test Case의 효과
자동화된 Test Case의 효과
 
테스트 케이스와 SW 품질
테스트 케이스와 SW 품질테스트 케이스와 SW 품질
테스트 케이스와 SW 품질
 
테스트 가능한 소프트웨어 설계와 TDD작성 패턴 (Testable design and TDD)
테스트 가능한 소프트웨어 설계와 TDD작성 패턴 (Testable design and TDD)테스트 가능한 소프트웨어 설계와 TDD작성 패턴 (Testable design and TDD)
테스트 가능한 소프트웨어 설계와 TDD작성 패턴 (Testable design and TDD)
 
테스트자동화 성공전략
테스트자동화 성공전략테스트자동화 성공전략
테스트자동화 성공전략
 
[2A4]DeepLearningAtNAVER
[2A4]DeepLearningAtNAVER[2A4]DeepLearningAtNAVER
[2A4]DeepLearningAtNAVER
 
Ai 그까이거
Ai 그까이거Ai 그까이거
Ai 그까이거
 
Ui test 자동화하기 - Selenium + Jenkins
Ui test 자동화하기 - Selenium + JenkinsUi test 자동화하기 - Selenium + Jenkins
Ui test 자동화하기 - Selenium + Jenkins
 
딥러닝과 강화 학습으로 나보다 잘하는 쿠키런 AI 구현하기 DEVIEW 2016
딥러닝과 강화 학습으로 나보다 잘하는 쿠키런 AI 구현하기 DEVIEW 2016딥러닝과 강화 학습으로 나보다 잘하는 쿠키런 AI 구현하기 DEVIEW 2016
딥러닝과 강화 학습으로 나보다 잘하는 쿠키런 AI 구현하기 DEVIEW 2016
 

Similar to Unit Test in Ruby on Rails by Minitest

Writing useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you buildWriting useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you build
Andrei Sebastian Cîmpean
 
Rails Testing
Rails TestingRails Testing
Rails Testing
mikeblake
 
Automated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choiceAutomated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choice
toddbr
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
Sergey Aganezov
 
Software Testing
Software TestingSoftware Testing
Software Testing
AdroitLogic
 
Introduction to testing in Rails
Introduction to testing in RailsIntroduction to testing in Rails
Introduction to testing in Rails
benlcollins
 
Defensive Apex Programming
Defensive Apex ProgrammingDefensive Apex Programming
Defensive Apex Programming
Salesforce Developers
 
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRWJest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Holger Grosse-Plankermann
 
Automated Testing with Databases
Automated Testing with DatabasesAutomated Testing with Databases
Automated Testing with Databaseselliando dias
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
Lilia Sfaxi
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
All Things Open
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2Tricode (part of Dept)
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql Server
David P. Moore
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
Eugene Dvorkin
 
Rspec Tips
Rspec TipsRspec Tips
Rspec Tipslionpeal
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4Billie Berzinskas
 
Testware Hierarchy for Test Automation
Testware Hierarchy for Test AutomationTestware Hierarchy for Test Automation
Testware Hierarchy for Test Automation
Gregory Solovey
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CI
wajrcs
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
Gil Fink
 
Tdd Ugialtnet Jan2010
Tdd Ugialtnet Jan2010Tdd Ugialtnet Jan2010
Tdd Ugialtnet Jan2010
guestcff805
 

Similar to Unit Test in Ruby on Rails by Minitest (20)

Writing useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you buildWriting useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you build
 
Rails Testing
Rails TestingRails Testing
Rails Testing
 
Automated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choiceAutomated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choice
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Introduction to testing in Rails
Introduction to testing in RailsIntroduction to testing in Rails
Introduction to testing in Rails
 
Defensive Apex Programming
Defensive Apex ProgrammingDefensive Apex Programming
Defensive Apex Programming
 
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRWJest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRW
 
Automated Testing with Databases
Automated Testing with DatabasesAutomated Testing with Databases
Automated Testing with Databases
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql Server
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
Rspec Tips
Rspec TipsRspec Tips
Rspec Tips
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4
 
Testware Hierarchy for Test Automation
Testware Hierarchy for Test AutomationTestware Hierarchy for Test Automation
Testware Hierarchy for Test Automation
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CI
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
 
Tdd Ugialtnet Jan2010
Tdd Ugialtnet Jan2010Tdd Ugialtnet Jan2010
Tdd Ugialtnet Jan2010
 

Recently uploaded

basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
NidhalKahouli2
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
symbo111
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABSDESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
itech2017
 
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
dxobcob
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Soumen Santra
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
ChristineTorrepenida1
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 
Water billing management system project report.pdf
Water billing management system project report.pdfWater billing management system project report.pdf
Water billing management system project report.pdf
Kamal Acharya
 
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
zwunae
 

Recently uploaded (20)

basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABSDESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
 
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 
Water billing management system project report.pdf
Water billing management system project report.pdfWater billing management system project report.pdf
Water billing management system project report.pdf
 
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
 

Unit Test in Ruby on Rails by Minitest

  • 2. • 코드 변경의 side effect를 초기에 파악할 수 있다... 등등의 일반적인 Unit Test의 필요성
 + • Rails Way를 자연스럽게 익힐 수 있다. • 즉, Rails Way를 따르지 않은 방식은 테스트에서 문제가 발생한다. WHY IS UNIT TEST NECESSARY / SO IMPORTANT?
  • 3. THINGS YOU SHOULD KNOW • 대부분의 레일스 애플리케이션은 데이터베이스와의 상호작용을 통해 동작하기 때문에 테스트 역시 데이터베이스를 필요로 한다. • 이러한 이유로 효과적인 테스트를 수행하기 위해서는 어떻게 데이터베이스를 세팅하고 샘플 데이터를 집어넣는 지에 대해서 이해할 필요가 있다. • 테스트를 위한 데이터베이스와 개발을 위한 데이터베이스를 함께 사용하는 경우 샘플 데 이터가 개발용 데이터를 망칠 수 있기 때문에 테스트용 데이터베이스를 별도로 두는 것 이 안전하다. 두어야만 한다.
  • 4. test/ 테스트 관련 파일들의 루트 디렉토리 models/ 모델관련 테스트 클래스들이 있는 디렉토리 controllers/ 컨트롤러관련 테스트 클래스들이 있는 디렉토리 integrations/ 여러개의 컨트롤러와 연관된 테스트 클래스들이 있는 디렉토리 helpers/ 헬퍼관련 테스트 클래스들이 있는 디렉토리 mailers/ 메일러관련 테스트 클래스들이 있는 디렉토리 fixtures/ 테스트 데이터들(fixture)이 들어있는 디렉토리 test_helper.rb 테스트와 관련된 기본 설정들을 담고 있는 클래스 DIRECTORIES FOR TEST IN RAILS
  • 5. RAKE TASKS FOR RUNNING YOUR TEST TASKS DESCRIPTION rake test Runs all tests in the test folder. You can also simply run rake as Rails will run all the tests by default rake test:controllers Runs all the controller tests from test/controllers rake test:functionals Runs all the functional tests from test/controllers, test/mailers, and test/functional rake test:helpers Runs all the helper tests from test/helpers rake test:integration Runs all the integration tests from test/integration rake test:jobs Runs all the job tests from test/jobs rake test:mailers Runs all the mailer tests from test/mailers rake test:models Runs all the model tests from test/models rake test:units Runs all the unit tests from test/models, test/helpers, and test/unit rake test:db Runs all tests in the test folder and resets the db
  • 7.  무엇인가? In software testing, a test fixture is a fixed state of the software under test used as a baseline for running tests; also known as the test context. https://en.wikipedia.org/wiki/Test_fixture#Software 테스트 픽서쳐란, 소프트웨어 테스트의 기준이 되는 고정된 상태값을 의미한다.
  • 9.  무엇인가? • 샘플(테스트) 데이터를 멋있게 부르는 말 • YAML 로 작성되어 있음. • 일종의 ActiveRecord object 라고 생각하면 됨 • Fixture 파일명은 테이블의 이름과 반드시 일치해야 한다. david: name: David Heinemeier Hansson birthday: 1979-10-15 profession: Systems development steve: name: Steve Ross Kellock birthday: 1974-09-27
  • 10. # In fixtures/categories.yml about: name: About # In fixtures/articles.yml one: title: Welcome to Rails! body: Hello world! category: about 픽스쳐(Fixtures)란
  • 11.  무엇인가? • 만약, fixture 안에서 association을 정의해야 하는 경우 아래와 같이 
 reference node 를 지정해 주면 됨. reference node belongs_to
  • 13.  무엇인가? • 만약, 픽스쳐파일의 확장자 끝에 .erb를 붙여주면 루비코드를 사용할 수 있다. • 루비코드를 이용하면 많은 양의 테스트 데이터를 손쉽게 생성할 수 있다. % 1000.times do |n| % user_%= n %: username: %= user#{n} % email: %= user#{n}@example.com % % end %
  • 15.  동작방식 • Rails는 test/fixtures 하위에 있는 모든 픽스쳐들을 세 단계에 걸쳐 로딩한다. 1. 픽스쳐에 해당하는 테이블의 기존 데이터를 삭제 한다. 2. 픽스쳐 데이터를 테이블에 로드 한다. 3. 픽스쳐 데이터에 직접 접근하고자 하는 경우에는 이를 변수에 덤프 한다. • 픽스쳐의 각 데이터는 아래와 같이 직접 접근이 가능하다. accessed by node name # In fixtures/users.yml david: name: David Heinemeier Hansson birthday: 1979-10-15 profession: Systems development # In test class users(:david) users(:david).id
  • 16. UNIT
  • 18.  for
  • 21. require 'test_helper'   class ArticleTest ActiveSupport::TestCase   # test the truth do   #   assert true   # end end DEFAULT
  • 25.  by
  • 26.  Rails • Minitest::Test 를 상속한 클래스에서는 test_ 로 시작하는 모든 메서드를 자동적으 로 테스트케이스로 인식하여 테스트 수행시 자동적으로 수행하게 된다. • Rails는 여기에 test 라는 이름의 메서드를 추가하였는데, 이 메서드는 [테스트 명]과 [블록] 을 받아서 이를 일반적인 Minitest::Unit으로 생성해 준다. 즉, 위의 코드에서 test “the truth” do... 는 실제로 아래와 같은 메서드를 생성한다. test_helper.rb : 모든 테스트에 공통적으로 적용되는 기본 설정을 정의하는 클래스 Minitest::Test ActiveSupport::TestCase ArticleTest def test_the_truth assert true end
  • 27. MODEL
  • 29.  IN
  • 31. require test_helper
 
 class ProductTest ActiveSupport::TestCase
 test product price must be positive do
 product = Product.new(title: My Book Title,
 description: yyy,
 image_url: zzz.jpg)
 product.price = -1
 assert product.invalid?, negative price of a product must be invalid.
 assert product.errors.has_key?(:price), an invalid product must have an error
 
 product.price = 0
 assert product.invalid?, negative price of a product must be invalid.
 assert product.errors.has_key?(:price), an invalid product must have an error
 
 product.price = 1
 assert product.valid?, positive price of a product must be valid.
 assert_empty product.errors, a valid product must have no error
 end
 end SIMPLE
  • 34.  CASE Product의 가격이 항상 0보다 커야함을 테스트. 가격이 -1, 0인 경우 모델은 invalid 해야 하고, error가 존재해야 함. 가격이 1인 경우 모델은 valid 해야 하고, error가 nil이어야 함. assertion의 두번재 파라미터는 해당 assertion이 실패했을 때 보여줄 메시지이다.
  • 35. $ rake test test/models/product_test.rb Run options: --seed 29214 # Running: E Finished in 0.042839s, 23.3433 runs/s, 0.0000 assertions/s. 1) Error: ProductTest#test_product_price_must_be_positive: NameError: uninitialized constant ProductTest::Product test/models/product_test.rb:5:in `block in class:ProductTest' 1 runs, 0 assertions, 0 failures, 1 errors, 0 skips TEST
  • 38.  #1
  • 39.  -
  • 40.  Error 테스트 실행 Product 모델이 없기 때문에 Error 발생 1개의 Test Case가 실행되어 1개의 Error가 발생
  • 41. $ rails g model Product title:string description:text image_url:string price:integer invoke active_record create db/migrate/20150814072826_create_products.rb create app/models/product.rb invoke test_unit conflict test/models/product_test.rb Overwrite /Users/hosang/01.work/git/jobplanet/test/models/product_test.rb? (enter h for help) [Ynaqdh] n skip test/models/product_test.rb create test/fixtures/products.yml $ RAILS_ENV=test rake db:migrate TEST
  • 44.  #1
  • 45.  -
  • 46.  FIX Product 모델 생성 기존에 이미 product_test.rb 파일이 존재하기 때문에 conflict 발생한다. n 키를 눌러서 skip db migration 실행
  • 47. $ rake test test/models/product_test.rb Run options: --seed 61999 # Running: F Finished in 0.050778s, 19.6935 runs/s, 19.6935 assertions/s. 1) Failure: ProductTest#test_product_price_must_be_positive [/Users/ hosang/01.work/git/jobplanet/test/models/product_test.rb:9]: negative price of a product must be invalid. 1 runs, 1 assertions, 1 failures, 0 errors, 0 skips TEST
  • 50.  #2
  • 51.  -
  • 52.  Failure 테스트 재실행 음수의 가격이 갖는 모델이 invalid 하다고 판단되지 않아서 assertion 실패 1개의 Test Case가 실행되어 1개의 assertion 가운데 1 개가 실패
  • 53. TEST
  • 56.  #2
  • 57.  -
  • 58.  FIX Product 모델에 :price attribute에 validation을 추가 class Product ActiveRecord::Base
 validates_numericality_of :price, greater_than: 0
 end
  • 59. $ rake test test/models/product_test.rb [DEPRECATION] Ahoy subscribers are deprecated Run options: --seed 47932 # Running: . Finished in 0.235739s, 4.2420 runs/s, 29.6939 assertions/s. 1 runs, 7 assertions, 0 failures, 0 errors, 0 skips TEST
  • 62.  #3
  • 63.  -
  • 64.  Pass 테스트 재실행 1개의 Test Case가 실행되어 총 7개의 assertion이 실패 없이 모두 수행됨.
  • 65. $ rake test test/models/product_test.rb [DEPRECATION] Ahoy subscribers are deprecated Run options: --seed 47932 # Running: . Finished in 0.235739s, 4.2420 runs/s, 29.6939 assertions/s. 1 runs, 7 assertions, 0 failures, 0 errors, 0 skips TEST
  • 68.  #3
  • 69.  -
  • 70.  Pass 테스트 재실행 1개의 Test Case가 실행되어 총 7개의 assertion이 실패 없이 모두 수행됨. WAIT!!
  • 71.  
  • 72.  
  • 73.  
  • 74.  
  • 75.  
  • 76.  7
  • 78.  
  • 79.  
  • 80.  
  • 81.  
  • 82.  
  • 83.  
  • 84.  
  • 85.  
  • 86.  
  • 87.  
  • 88.  
  • 89.  
  • 90.  
  • 91.  
  • 93. $ rake test test/models/product_test.rb [DEPRECATION] Ahoy subscribers are deprecated Run options: --seed 47932 # Running: . Finished in 0.235739s, 4.2420 runs/s, 29.6939 assertions/s. 1 runs, 7 assertions, 0 failures, 0 errors, 0 skips TEST
  • 96.  #3
  • 97.  -
  • 98.  Pass 테스트 재실행 1개의 Test Case가 실행되어 총 7개의 assertion이 실패 없이 모두 수행됨. def assert_empty obj, msg = nil
 msg = message(msg) { Expected #{mu_pp(obj)} to be empty }
 assert_respond_to obj, :empty?
 assert obj.empty?, msg
 end assert_empty는
  • 104.  TEST
  • 105.  for
  • 106.  YOUR
  • 110.  TEST
  • 111.  CASE
  • 113.  by
  • 114.  Rails test_helper.rb : 모든 테스트에 공통적으로 적용되는 기본 설정을 정의하는 클래스 Minitest::Test ActiveSupport::TestCase ArticleTest require 'test_helper'
 
 class ArticlesControllerTest ActionController::TestCase
 setup do
 @article = articles(:one)
 end
 
 test should get index do
 get :index
 assert_response :success
 end
 end Because we redirect the route unless user has logged in. If you have a authentication checking filter using Devise before this action, then this test case will be failed. WYH?
  • 115. SIMPLE
  • 117.  TEST
  • 118.  CASE 3) WORKS FINE ENV['RAILS_ENV'] ||= 'test'
 require File.expand_path('../../config/environment', __FILE__)
 require 'rails/test_help'
 
 class ActiveSupport::TestCase
 # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
 fixtures :all
 
 # Add more helper methods to be used by all tests here...
 end
 
 # https://github.com/plataformatec/devise
 class ActionController::TestCase
 include Devise::TestHelpers
 end require 'test_helper'
 
 class ArticlesControllerTest ActionController::TestCase
 setup do
 @article = articles(:one)
 sign_in users(:one)
 end
 
 test should get index do
 get :index
 assert_response :success
 end
 end 1) Include Devise Helper in test_helper.rb file 2) Sign In
  • 120.  TEST
  • 121. $ bin/rails generate minitest:feature CanSignupNewUser create test/features/can_signup_new_user_test.rb Integration
  • 122.  Test
  • 123.  는
  • 125.  가
  • 133.  함 test/features 디렉터리에 새로운 feature test case 가 생성 됨. Minitest
  • 134.  의
  • 141.  이용함. ENV['RAILS_ENV'] ||= 'test'
 require File.expand_path('../../config/environment', __FILE__)
 require 'rails/test_help'
 require minitest/rails/capybara
 
 class ActiveSupport::TestCase
 # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
 fixtures :all
 
 # Add more helper methods to be used by all tests here...
 end
 
 # https://github.com/plataformatec/devise
 class ActionController::TestCase
 include Devise::TestHelpers
 end
 
 # https://github.com/blowmage/minitest-rails-capybara
 class ActionDispatch::IntegrationTest
 include Capybara::DSL
 include Capybara::Assertions
 end 1) Include Capybara
  • 142. SIGN
  • 143.  UP
  • 145.  TEST require test_helper
 
 class SignupTest Capybara::Rails::TestCase
 test can signup with email do
 # 1. Visit landing page
 # 2. enter email and password (twice)
 # 3. click register button
 # 4. Success 
 end
 end WRITE SCENARIO
  • 146. SIGN
  • 147.  UP
  • 149.  TEST require test_helper
 
 class SignupTest Capybara::Rails::TestCase
 test can signup with email do
 # 1. Visit landing page
 visit root_path
 
 # 2. enter email and password (twice)
 page.fill_in 'user[email]', with: #{Time.now.to_i}@test.com
 page.fill_in 'user[password]', with: qwer1234
 page.fill_in 'user[password_confirmation]', with: qwer1234
 
 # 3. click register button
 page.find(‘#btn_sign_up').click
 
 # 4. Success
 assert_equal 200, page.status_code
 end
 end WRITE TEST CODES 참고: Capybara TestCase 에서는 Rails Specific assert 를 사용할 수 없음.
  • 151. AVAILABLE ASSERTIONS CAN BE USED WITH MINITEST (1/3) ASSERTIONS PURPOSE assert( test, [msg] ) Ensures that test is true. assert_not( test, [msg] ) Ensures that test is false. assert_equal( expected, actual, [msg] ) Ensures that expected == actual is true. assert_not_equal( expected, actual, [msg] ) Ensures that expected != actual is true. assert_same( expected, actual, [msg] ) Ensures that expected.equal?(actual) is true. assert_not_same( expected, actual, [msg] ) Ensures that expected.equal?(actual) is false. assert_nil( obj, [msg] ) Ensures that obj.nil? is true. assert_not_nil( obj, [msg] ) Ensures that obj.nil? is false. assert_empty( obj, [msg] ) Ensures that obj is empty?. assert_not_empty( obj, [msg] ) Ensures that obj is not empty?. assert_match( regexp, string, [msg] ) Ensures that a string matches the regular expression. assert_no_match( regexp, string, [msg] ) Ensures that a string doesn't match the regular expression. assert_includes( collection, obj, [msg] ) Ensures that obj is in collection. assert_not_includes( collection, obj, [msg] ) Ensures that obj is not in collection. assert_in_delta( expecting, actual, [delta], [msg] ) Ensures that the numbers expected and actual are within delta of each other. assert_not_in_delta( expecting, actual, [delta], [msg] ) Ensures that the numbers expected and actual are not within delta of each other.
  • 152. AVAILABLE ASSERTIONS CAN BE USED WITH MINITEST (2/3) ASSERTIONS PURPOSE assert_throws( symbol, [msg] ) { block } Ensures that the given block throws the symbol. assert_raises( exception1, exception2, ... ) { block } Ensures that the given block raises one of the given exceptions. assert_nothing_raised( exception1, exception2, ... ) { block } Ensures that the given block doesn't raise one of the given exceptions. assert_instance_of( class, obj, [msg] ) Ensures that obj is an instance of class. assert_not_instance_of( class, obj, [msg] ) Ensures that obj is not an instance of class. assert_kind_of( class, obj, [msg] ) Ensures that obj is or descends from class. assert_not_kind_of( class, obj, [msg] ) Ensures that obj is not an instance of class and is not descending from it. assert_respond_to( obj, symbol, [msg] ) Ensures that obj responds to symbol. assert_not_respond_to( obj, symbol, [msg] ) Ensures that obj does not respond to symbol. assert_operator( obj1, operator, [obj2], [msg] ) Ensures that obj1.operator(obj2) is true. assert_not_operator( obj1, operator, [obj2], [msg] ) Ensures that obj1.operator(obj2) is false. assert_predicate ( obj, predicate, [msg] ) Ensures that obj.predicate is true, e.g. assert_predicate str, :empty? assert_not_predicate ( obj, predicate, [msg] ) Ensures that obj.predicate is false, e.g. assert_not_predicate str, :empty? assert_send( array, [msg] ) Ensures that executing the method listed in array[1] on the object in array[0] with the parameters of array[2 and up] is true. This one is weird eh? flunk( [msg] ) Ensures failure. This is useful to explicitly mark a test that isn't finished yet.
  • 153. AVAILABLE ASSERTIONS CAN BE USED WITH MINITEST (3/3) RAILS SPECIFIC ASSERTIONS PURPOSE assert_difference(expressions, difference = 1, message = nil) {...} Test numeric difference between the return value of an expression as a result of what is evaluated in the yielded block. assert_no_difference(expressions, message = nil, amp;block) Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block. assert_recognizes(expected_options, path, extras={}, message=nil) Asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that assert_generates(expected_path, options, defaults={}, extras = {}, message=nil) Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. The extras parameter is used to tell the request the assert_response(type, message = nil) Asserts that the response comes with a specific status code. You can specify :success to indicate 200-299, :redirectto indicate 300-399, :missing to assert_redirected_to(options = {}, message=nil) Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such that assert_template(expected = nil, message=nil) Asserts that the request was rendered with the appropriate template file. assert_difference(expressions, difference = 1, message = nil) {...} Test numeric difference between the return value of an expression as a result of what is evaluated in the yielded block. assert_no_difference(expressions, message = nil, amp;block) Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block. assert_recognizes(expected_options, path, extras={}, message=nil) Asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that assert_generates(expected_path, options, defaults={}, extras = {}, message=nil) Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. The extras parameter is used to tell the request the assert_response(type, message = nil) Asserts that the response comes with a specific status code. You can specify :success to indicate 200-299, :redirectto indicate 300-399, :missing to assert_redirected_to(options = {}, message=nil) Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such that assert_template(expected = nil, message=nil) Asserts that the request was rendered with the appropriate template file.
  • 154. REFERENCES A Guide to Testing Rails Applications: 
 http://guides.rubyonrails.org/testing.html 
 Capybara: 
 https://github.com/jnicklas/capybara