Rails makes it easy to write your tests with Minitest (A default testing framework used by rails).
This slide contains contents about:
1. WHY IS UNIT TEST NECESSARY / SO IMPORTANT?
- Unit Test make it easy to learn Rails Way.
2. THINGS YOU SHOULD KNOW
- You need to have database for test environment.
3. DIRECTORIES FOR TEST IN RAILS
4. WHAT IS FIXTURES?
5. MODEL TEST IN ACTION
- test_helper.rb
- Youre Test Case < ActiveSupport::TestCase < Minitest::Test
- A simple approach for TDD (Test Driven Development)
6. AVAILABLE ASSERTIONS
레일스는 Minitest 를 기본 테스팅 프레임워크로 포함하고 있습니다.
이 슬라이드에서는 미니테스트와 관련된 레일스 단위 테스트 관련 기본 개념에 대해서 설명합니다.
또한, 간단한 모델 테스트 케이스를 이용하여 실제 테스트를 수행하는 방법에 대해서 간략히 설명합니다.
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)Jen Wong
FitNesse is a wiki-based software testing tool that can be a powerful addition to your Continuous Integration Environments. Its greatest advantages include providing visibility into tests and results, and providing access to test-writing by non-technical team members. We will:
* look at specific examples and code,
* discuss the advantages and drawbacks of using FitNesse as a test framework
* implement, deploy, and use a simple fixture in a fitnesse test
* review different kinds of fixtures, including decision table, script, query, html, and selenium webtest fixtures
* discuss some of the more interesting fixture extensions we've implemented, including JSON-based verification and the ability to pass in javascript code for dynamic verification
* use Hudson/Jenkins to run your FitNesse tests as a step in your Continuous Integration/Deployment process
Principles and patterns for test driven developmentStephen Fuqua
Developed to help introduce key topics in Test Driven Development, for new and veteran developers alike. Some examples are language-specific (C# / MSTest / Moq), but the principles apply to any object oriented language.
Unit tests give developers and testers a quick way to look for logic errors in the methods of classes in Visual C#, Visual Basic, and Visual C++ projects. A unit test can be created one time and run every time that source code is changed to make sure that no bugs are introduced.
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)Jen Wong
FitNesse is a wiki-based software testing tool that can be a powerful addition to your Continuous Integration Environments. Its greatest advantages include providing visibility into tests and results, and providing access to test-writing by non-technical team members. We will:
* look at specific examples and code,
* discuss the advantages and drawbacks of using FitNesse as a test framework
* implement, deploy, and use a simple fixture in a fitnesse test
* review different kinds of fixtures, including decision table, script, query, html, and selenium webtest fixtures
* discuss some of the more interesting fixture extensions we've implemented, including JSON-based verification and the ability to pass in javascript code for dynamic verification
* use Hudson/Jenkins to run your FitNesse tests as a step in your Continuous Integration/Deployment process
Principles and patterns for test driven developmentStephen Fuqua
Developed to help introduce key topics in Test Driven Development, for new and veteran developers alike. Some examples are language-specific (C# / MSTest / Moq), but the principles apply to any object oriented language.
Unit tests give developers and testers a quick way to look for logic errors in the methods of classes in Visual C#, Visual Basic, and Visual C++ projects. A unit test can be created one time and run every time that source code is changed to make sure that no bugs are introduced.
For a number of years now we have been hearing about all of the benefits that automated unit testing provides like increasing our quality, catching errors earlier, ensuring that all developers are testing in the same manner and deploying updates with high confidence that nothing will break. Testing a Web UI though was difficult and fragile which meant that typically we had no automated unit test for our Web UI. This is no longer the case with the latest release of Angular. Unit testing is now a first class citizen in Angular.
Out of the box, the project generated by the Angular CLI has unit testing setup with Karma and Jasmine and includes sample tests. Generating new components, services, and pipes includes the unit test Spec file already wired up. Thus allowing you to focus on writing your unit tests and not on the infrastructure needed to get them running. The barriers to writing unit test have been destroyed.
This talk will walk through getting started unit testing your Angular components, services, and pipes. Along the way I will share the tips and tricks that I have learned as I have implemented unit testing on my Angular projects at a Fortune 100 company. You will walk away ready to immediately implement unit testing on your Angular project.
Refactoring Legacy Web Forms for Test AutomationStephen Fuqua
THE CHALLENGE:
Given you understand the value of test automation.
Given you are handed a legacy application to maintain and enhance
Given the application is in ASP.Net Web Forms
When you try to add tests
Then you find that test-driven development is literally impossible.
How Testability Inspires AngularJS Design / Ran MizrahiRan Mizrahi
Testability is a major part of design decision making in Angular`s development.
In this sessions we’ll cover what testability is, how it inspires Angular`s design and why it’s good for us.
Angular Unit Testing from the TrenchesJustin James
For a number of years now we have been hearing about all of the benefits that automated unit testing provides like increasing our quality, catching errors earlier, ensuring that all developers are testing in the same manner and deploying updates with high confidence that nothing will break. Testing a Web UI though was difficult and fragile which meant that typically we had no automated unit test for our Web UI. This is no longer the case with the latest release of Angular. Unit testing is now a first class citizen in Angular.
Out of the box, the project generated by the Angular CLI has unit testing setup with Karma and Jasmine and includes sample tests. Generating new components, services, and pipes includes the unit test Spec file already wired up. Thus allowing you to focus on writing your unit tests and not on the infrastructure needed to get them running. The barriers to writing unit test have been destroyed.
This talk will walk through getting started unit testing your Angular components, services, and pipes. Along the way I will share the tips and tricks that I have learned as I have implemented unit testing on my Angular projects at a Fortune 100 company. You will walk away ready to immediately implement unit testing on your Angular project.
Oh so you test? - A guide to testing on Android from Unit to MutationPaul Blundell
Everyone knows you need testing, but what are the different types of testing, how will each type benefit you and what libraries are available to ease the pain? This talk will run through an explanation of each type of testing (unit, integration, functional, acceptance, fuzz, mutation...) explaining upon each level of an Android app, the testing involved, how this will benefit you and how it will benefit your users. It will also explain the architecture of a well tested app. Finally ending with some examples and libraries that ease your accessibility into testing and help with faster more descriptive feedback.
In this session the current automated testing infrastructure of the Joomla CMS is explained:
theory of system- & unit-tests
Joomla's unit testing setup
setting up your machine
how to execute the test suite
how to write a test
Joomla's system testing setup
setting up your machine
how to execute the test suite
how Joomla automates the automated tests
The presentation contains a definition and survey of the benefits of Unit Testing, and a little coding example to get the feeling of Unit Testing using JUnit, EasyMock and XMLUnit.
For a number of years now we have been hearing about all of the benefits that automated unit testing provides like increasing our quality, catching errors earlier, ensuring that all developers are testing in the same manner and deploying updates with high confidence that nothing will break. Testing a Web UI though was difficult and fragile which meant that typically we had no automated unit test for our Web UI. This is no longer the case with the latest release of Angular. Unit testing is now a first class citizen in Angular.
Out of the box, the project generated by the Angular CLI has unit testing setup with Karma and Jasmine and includes sample tests. Generating new components, services, and pipes includes the unit test Spec file already wired up. Thus allowing you to focus on writing your unit tests and not on the infrastructure needed to get them running. The barriers to writing unit test have been destroyed.
This talk will walk through getting started unit testing your Angular components, services, and pipes. Along the way I will share the tips and tricks that I have learned as I have implemented unit testing on my Angular projects at a Fortune 100 company. You will walk away ready to immediately implement unit testing on your Angular project.
Refactoring Legacy Web Forms for Test AutomationStephen Fuqua
THE CHALLENGE:
Given you understand the value of test automation.
Given you are handed a legacy application to maintain and enhance
Given the application is in ASP.Net Web Forms
When you try to add tests
Then you find that test-driven development is literally impossible.
How Testability Inspires AngularJS Design / Ran MizrahiRan Mizrahi
Testability is a major part of design decision making in Angular`s development.
In this sessions we’ll cover what testability is, how it inspires Angular`s design and why it’s good for us.
Angular Unit Testing from the TrenchesJustin James
For a number of years now we have been hearing about all of the benefits that automated unit testing provides like increasing our quality, catching errors earlier, ensuring that all developers are testing in the same manner and deploying updates with high confidence that nothing will break. Testing a Web UI though was difficult and fragile which meant that typically we had no automated unit test for our Web UI. This is no longer the case with the latest release of Angular. Unit testing is now a first class citizen in Angular.
Out of the box, the project generated by the Angular CLI has unit testing setup with Karma and Jasmine and includes sample tests. Generating new components, services, and pipes includes the unit test Spec file already wired up. Thus allowing you to focus on writing your unit tests and not on the infrastructure needed to get them running. The barriers to writing unit test have been destroyed.
This talk will walk through getting started unit testing your Angular components, services, and pipes. Along the way I will share the tips and tricks that I have learned as I have implemented unit testing on my Angular projects at a Fortune 100 company. You will walk away ready to immediately implement unit testing on your Angular project.
Oh so you test? - A guide to testing on Android from Unit to MutationPaul Blundell
Everyone knows you need testing, but what are the different types of testing, how will each type benefit you and what libraries are available to ease the pain? This talk will run through an explanation of each type of testing (unit, integration, functional, acceptance, fuzz, mutation...) explaining upon each level of an Android app, the testing involved, how this will benefit you and how it will benefit your users. It will also explain the architecture of a well tested app. Finally ending with some examples and libraries that ease your accessibility into testing and help with faster more descriptive feedback.
In this session the current automated testing infrastructure of the Joomla CMS is explained:
theory of system- & unit-tests
Joomla's unit testing setup
setting up your machine
how to execute the test suite
how to write a test
Joomla's system testing setup
setting up your machine
how to execute the test suite
how Joomla automates the automated tests
The presentation contains a definition and survey of the benefits of Unit Testing, and a little coding example to get the feeling of Unit Testing using JUnit, EasyMock and XMLUnit.
저는 핀테크 서비스 개발 프로젝트에 참여하여 CI 구축과 QA 자동화 부분 개발을 담당하였습니다.
프로젝트가 시작하면 수 많은 개발자들과 기획자 그리고 QA 들이 다투는 것은 빈번한 일상입니다..
바쁜 개발 과정에서 기본적인 로그인 함수의 구현을 계속해서 체크해야 하는 것은 매우 불편하고 번거롭죠.
Selenium과 Jenkins를 통해 다음과 같은 상황을 자동화하여 개발자들과 QA/기획자들간의 갈등을 줄이고자 합니다.
스크린샷 중 가린부분들은 현재 회사 프로젝트 유출 방지를 위한 것이니 너그러이 용서해주시길..
딥러닝과 강화 학습으로 나보다 잘하는 쿠키런 AI 구현하기 DEVIEW 2016Taehoon Kim
발표 영상 : https://goo.gl/jrKrvf
데모 영상 : https://youtu.be/exXD6wJLJ6s
Deep Q-Network, Double Q-learning, Dueling Network 등의 기술을 소개하며, hyperparameter, debugging, ensemble 등의 엔지니어링으로 성능을 끌어 올린 과정을 공유합니다.
Writing useful automated tests for the single page applications you buildAndrei Sebastian Cîmpean
How to approach testing if you are building a modern single page application. I try to emphasize that integration testing is the way to go and that developers should consider the tests as part of the system and spend time to maintain them.
Automated Acceptance Testing (and tool choice)
Automated acceptance testing has many names: acceptance-test driven development (ATDD), story-test driven development (STDD), agile acceptance testing and, most recently, specification by example. At the heart of all these approaches is to produce business-facing tests which are system tests running end-to-end, picking up regression issues and improving confidence that the code works as required.
In this talk, I will contextualise how each of these approaches share in common a three-tier layering strategy: acceptance criteria, test implementation layer and application driver layer. This is important because applying this approach requires a tool choice and each tool tends to have its own sweet (and blind) spot that is best understood through these layers.
I will first deep dive into sample code across a few tools (Cucumber, Fitnesse, Concordion) to illustrate this layering. I use an example that shows how to decouple the GUI from tests (window driver pattern).
Finally, I will look at some typical client scenarios to examine which tools might best suited because tool choice is not simply a host operating system question (.Net, Java, Ruby).
We investigate one of the most popular approaches to creating software: test driven development. From the basic understanding why tests are important to a new software development paradigm, where you start with tests and them do the implementation. We glance over different areas of testing and see how one should really do the software testing in different situation.
Software testing
Developers Belief on Software Testing
Developers Responsibility for testing
Test writing methods
State based testing
Behavioural/interaction based testing
Writing a Testable Code
Flaw 1 - Constructor does Real Work
Flaw 2 - API lies about it's real dependencies
Flaw 3 - Brittle Global State & Singletons
Testing Frameworks and tools for Java...
Mockito and PowerMock...
Testing Models
Stubs Based Testing Model
Mocked Objects Based Testing Model
JUit 4.+ and TestNG
https://www.adroitlogic.com
https://developer.adroitlogic.com
Have you ever finished writing unit tests and deploying to production, only to get errors or problems later down the line? If you want to learn how to minimize these kinds of data problems or failures before they occur, you need to program defensively. Join us to learn about Apex design patterns for resilient code, how to build applications that monitor themselves, and how to avoid common mistakes that even experienced developers make.
Mal ganz ehrlich: Testen im Frontend hat noch nie viel Spaß gemacht. In meinem Talk möchte ich mit Jest eine Testbibliothek vorstellen, die genau das ändern kann. Jest ist ohne viel Konfiguration direkt einsetzbar und bringt alles mit, was man von einer Testbibliothek erwartet (und noch mehr). An vielen praktischen Beispielen möchte ich meine Lieblingsfeatures wie z.B. Snapshot-Tests, Mocking oder das tolle CLI erläutern und zeigen, dass Testen im Frontend durchaus Spaß machen kann. Eine Ausrede weniger, um auf das Testen im Frontend zu verzichten!
Test Driven Development, or TDD, is the mainstream in many areas of software development, but what about the database? In this session, we explore TDD, the benefits of automated testing, and how testing data projects differs from other types of development. We introduce the tSQLt testing framework and demonstrate its use with a live coding example. Finally, we will discuss some lessons learned in doing TDD with SQL Server.
Originally presented by Steve Fibich and David Moore at Richmond SQL Server Users Group on January 11, 2018
First Section:
Continuous Delivery as a software engineering approach.
(This is beneficial for Project Managers, DEVs & QAs.)
1. Projects Case Studies to explain why you should adopt Continuous Delivery.
2. Advantages & Reasons for releasing software more frequently.
3. How to make a Reliable / Production Ready Software.
4. Ingredients of Continues Delivery.
5. Tools/ approaches to choose while using Continues Delivery Methodology.
Second Section:
Technical side of Continuous Delivery.
(This is more beneficial for DEVs/ QAs than Project Managers.)
1. Testing a Software.
2. Measuring Code Quality / Analytic to visualize teams performances.
3. Tools: Code Syntax Checker, Testing Framework, Build Automation, Automated Reporting/ Analytic Dashboard.
4. Continuous Delivery Automation over Cloud using Travis CI - Live demonstration.
Third Section:
1. Sample Projects for audience to adopt right tools for development, testing & deployments.
2. Q&A.
-------------------------------------------------
By Waqar Alamgir http://waqaralamgir.tk
HEAP SORT ILLUSTRATED WITH HEAPIFY, BUILD HEAP FOR DYNAMIC ARRAYS.
Heap sort is a comparison-based sorting technique based on Binary Heap data structure. It is similar to the selection sort where we first find the minimum element and place the minimum element at the beginning. Repeat the same process for the remaining elements.
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Dr.Costas Sachpazis
Terzaghi's soil bearing capacity theory, developed by Karl Terzaghi, is a fundamental principle in geotechnical engineering used to determine the bearing capacity of shallow foundations. This theory provides a method to calculate the ultimate bearing capacity of soil, which is the maximum load per unit area that the soil can support without undergoing shear failure. The Calculation HTML Code included.
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsVictor Morales
K8sGPT is a tool that analyzes and diagnoses Kubernetes clusters. This presentation was used to share the requirements and dependencies to deploy K8sGPT in a local environment.
Student information management system project report ii.pdfKamal Acharya
Our project explains about the student management. This project mainly explains the various actions related to student details. This project shows some ease in adding, editing and deleting the student details. It also provides a less time consuming process for viewing, adding, editing and deleting the marks of the students.
Forklift Classes Overview by Intella PartsIntella Parts
Discover the different forklift classes and their specific applications. Learn how to choose the right forklift for your needs to ensure safety, efficiency, and compliance in your operations.
For more technical information, visit our website https://intellaparts.com
Water billing management system project report.pdfKamal Acharya
Our project entitled “Water Billing Management System” aims is to generate Water bill with all the charges and penalty. Manual system that is employed is extremely laborious and quite inadequate. It only makes the process more difficult and hard.
The aim of our project is to develop a system that is meant to partially computerize the work performed in the Water Board like generating monthly Water bill, record of consuming unit of water, store record of the customer and previous unpaid record.
We used HTML/PHP as front end and MYSQL as back end for developing our project. HTML is primarily a visual design environment. We can create a android application by designing the form and that make up the user interface. Adding android application code to the form and the objects such as buttons and text boxes on them and adding any required support code in additional modular.
MySQL is free open source database that facilitates the effective management of the databases by connecting them to the software. It is a stable ,reliable and the powerful solution with the advanced features and advantages which are as follows: Data Security.MySQL is free open source database that facilitates the effective management of the databases by connecting them to the software.
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
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
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
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
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
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는
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?
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
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
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
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