0% found this document useful (0 votes)
10 views49 pages

Codeigniter Testing Guide Beginners Guide To Automated Testing in PHP Kenji Suzuki Download

The document is a guide titled 'CodeIgniter Testing Guide: Beginners' Guide to Automated Testing in PHP' by Kenji Suzuki and Mat Whitney, focusing on automated testing in PHP applications using the CodeIgniter framework. It covers topics such as setting up the testing environment, understanding test jargon, and the importance of writing test code. Additionally, it provides links to related resources and other recommended books on CodeIgniter.

Uploaded by

umbroagansyq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views49 pages

Codeigniter Testing Guide Beginners Guide To Automated Testing in PHP Kenji Suzuki Download

The document is a guide titled 'CodeIgniter Testing Guide: Beginners' Guide to Automated Testing in PHP' by Kenji Suzuki and Mat Whitney, focusing on automated testing in PHP applications using the CodeIgniter framework. It covers topics such as setting up the testing environment, understanding test jargon, and the importance of writing test code. Additionally, it provides links to related resources and other recommended books on CodeIgniter.

Uploaded by

umbroagansyq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Codeigniter Testing Guide Beginners Guide To

Automated Testing In Php Kenji Suzuki download

https://ebookbell.com/product/codeigniter-testing-guide-
beginners-guide-to-automated-testing-in-php-kenji-suzuki-5323080

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Codeigniter 17 Jose Argudo Blanco David Upton

https://ebookbell.com/product/codeigniter-17-jose-argudo-blanco-david-
upton-2008694

Codeigniter 17 Professional Development Adam Griffith

https://ebookbell.com/product/codeigniter-17-professional-development-
adam-griffith-2269460

Codeigniter For Rapid Php Application Development 1st Edition David


Upton

https://ebookbell.com/product/codeigniter-for-rapid-php-application-
development-1st-edition-david-upton-37727030

Codeigniter 2 Cookbook Rob Foster

https://ebookbell.com/product/codeigniter-2-cookbook-rob-
foster-4684162
Codeigniter Web Application Blueprints Develop Fullfeatured Dynamic
Web Applications Using The Powerful Codeigniter Mvc Framework Rob
Foster

https://ebookbell.com/product/codeigniter-web-application-blueprints-
develop-fullfeatured-dynamic-web-applications-using-the-powerful-
codeigniter-mvc-framework-rob-foster-5467510

Professional Codeigniter Wrox Professional Guides 1st Edition Thomas


Myer

https://ebookbell.com/product/professional-codeigniter-wrox-
professional-guides-1st-edition-thomas-myer-2539010

Practical Codeigniter 3 1st Edition Lonnie Ezell

https://ebookbell.com/product/practical-codeigniter-3-1st-edition-
lonnie-ezell-12011072
Kenji Suzuki and Mat Whitney
CodeIgniter Testing Guide
Beginners’ Guide to Automated Testing in PHP.

Kenji Suzuki and Mat Whitney


© 2015 - 2016 Kenji Suzuki and Mat Whitney
Tweet This Book!
Please help Kenji Suzuki and Mat Whitney by spreading the word about this book on Twitter!
The suggested hashtag for this book is #CITestGuide.
Find out what other people are saying about the book by clicking on this link to search for this
hashtag on Twitter:
https://twitter.com/search?q=#CITestGuide
Contents

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i
The Book at a Glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i
What You Need for This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii
Who should read This Book? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii
Why PHPUnit? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv
Is This a CodeIgniter Book? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv
Is Testing PHP Applications Difficult? . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv
Is Testing CodeIgniter Applications Difficult? . . . . . . . . . . . . . . . . . . . . v
Testing is Fun and Easy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v
Conventions Used in This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v
Errata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii

1. What is Automated Testing? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1


1.1 Primitive Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Manual Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Automated Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Why should you write test code? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Finding the Middle Way . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 What should you test? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5 TDD or Not TDD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2. Setting Up the Testing Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7


2.1 Installing CodeIgniter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 Installing ci-phpunit-test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Enabling Monkey Patching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.3 (Optional) Installing VisualPHPUnit . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Installing Composer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Installing VisualPHPUnit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Installing PHPUnit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Configuring VisualPHPUnit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Configuring PHPUnit XML Configuration File . . . . . . . . . . . . . . . . . . . 11
2.4 Installing PHPUnit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.5 (Optional) Installing PsySH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.6 Installing via Composer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
CONTENTS

Installing Composer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Installing CodeIgniter via Composer . . . . . . . . . . . . . . . . . . . . . . . . . 14
Installing ci-phpunit-test via Composer . . . . . . . . . . . . . . . . . . . . . . . 14
Installing PHPUnit via Composer . . . . . . . . . . . . . . . . . . . . . . . . . . 15
(Optional) Installing PsySH via Composer . . . . . . . . . . . . . . . . . . . . . . 16

3. Test Jargon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.1 Testing levels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Unit Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Integration Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
System Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.2 Testing Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Functional Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Database Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Browser Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Acceptance Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.3 Code Coverage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.4 Fixtures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.5 Test Doubles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Mocks and Stubs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

4. PHPUnit Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
4.1 Running PHPUnit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Running All Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Running a Specific Test Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.2 Running PHPUnit via Web Browser . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Running Web Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Running All Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Running a Specific Test Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.3 Configuring PHPUnit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
XML Configuration File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Command Line Arguments and Options . . . . . . . . . . . . . . . . . . . . . . 30
4.4 Understanding the Basics by Testing Libraries . . . . . . . . . . . . . . . . . . . . . 33
Basic Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Data Provider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Fixtures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Assertions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

5. Testing a Simple MVC Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46


5.1 Functional Testing for Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Controller to Handle Static Pages . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Manual Testing with a Web Browser . . . . . . . . . . . . . . . . . . . . . . . . 49
Test Case for Page Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
CONTENTS

Checking Code Coverage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53


5.2 Database Testing for Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Preparing the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
News Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Manual Testing with a Web Browser . . . . . . . . . . . . . . . . . . . . . . . . 64
Database Fixtures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Test Case for the News Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Checking Code Coverage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

6. Unit Testing for Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75


6.1 Why Should You Test Models First? . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6.2 PHPUnit Mock Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Playing with Mocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Partial Mocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Verifying Expectations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
6.3 Testing Models without Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Testing the get_news() Method with Mocks . . . . . . . . . . . . . . . . . . . . . 81
Testing the set_news() Method with Mocks . . . . . . . . . . . . . . . . . . . . . 90
6.4 With the Database or Without the Database? . . . . . . . . . . . . . . . . . . . . . 94
Testing with Little Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
When You Write Tests without the Database . . . . . . . . . . . . . . . . . . . . 96

7. Testing Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
7.1 Why is Testing Controllers Difficult? . . . . . . . . . . . . . . . . . . . . . . . . . . 98
7.2 Test Case for the News Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
7.3 Mocking Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
7.4 Authentication and Redirection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Installing Ion Auth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Manual Testing with a Web Browser . . . . . . . . . . . . . . . . . . . . . . . . 109
Testing Redirection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Mocking Auth Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
7.5 What if My Controller Needs Something Else? . . . . . . . . . . . . . . . . . . . . . 113

8. Unit Testing CLI Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115


8.1 Dbfixture Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
8.2 Faking is_cli() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
8.3 Testing exit() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
8.4 Testing Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
8.5 Testing Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
8.6 Monkey Patching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Patching Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Patching Class Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
8.7 Checking Code Coverage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
CONTENTS

9. Testing REST Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127


9.1 Installing CodeIgniter Rest Server . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Fixing the CodeIgniter Rest Server Code . . . . . . . . . . . . . . . . . . . . . . 127
9.2 Testing GET Requests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Getting All of the Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Getting One User’s Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
9.3 Adding Request Headers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
9.4 Testing POST Requests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
9.5 Testing JSON Requests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
9.6 Testing DELETE Requests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136

10. Browser Testing with Codeception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139


10.1 Installing and Configuring Codeception . . . . . . . . . . . . . . . . . . . . . . . . 139
What is Codeception? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Installing Codeception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
What is Selenium Server? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Installing Selenium Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Initializing Codeception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Configuring Acceptance Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
10.2 Writing Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
Conventions for Codeception Acceptance Tests . . . . . . . . . . . . . . . . . . . 142
Writing Our First Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
10.3 Running Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Running Selenium Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Running the Web Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Running Codeception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
10.4 Browser Testing: Pros and Cons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
10.5 Database Fixtures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
10.6 Test Case for the News Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Database Fixtures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Testing Page Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Testing Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
NewsCept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
10.7 Testing with Google Chrome . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
Installing the ChromeDriver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
Configuring Acceptance Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
Running Selenium Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Running Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153

11. Congratulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156

Appendix A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
How to Speed Up Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
CONTENTS

Speed Up without Code Modifications . . . . . . . . . . . . . . . . . . . . . . . 157

Appendix B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
How to Read ci-phpunit-test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Structure of ci-phpunit-test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Bootstrap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
Autoloader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
Replaced Classes and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
New Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
TestCase classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
Request related classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
Helper classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
Monkey Patch library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166

Appendix C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
License Agreement for CodeIgniter and its User Guide . . . . . . . . . . . . . . . . . . . 168
License Agreement for CodeIgniter Rest Server . . . . . . . . . . . . . . . . . . . . . . . 169
License Agreement for Ion Auth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
Preface
When I learned PHP for the first time, I did not know about writing test code at all. Nobody
around me was writing test code. There was no PHPUnit (a testing framework for PHP), yet. In
2004, PHPUnit 1.0.0 was released for PHP4. In the same year, PHPUnit 2.0.0 was released for PHP5.
However, I have never used PHPUnit 1 or 2.
When I found CodeIgniter (a PHP web application framework) for the first time, in 2007, it had a
Unit testing class, but there was no test code for the framework itself.
Now, in 2015, more than 10 years have passed since PHPUnit 1.0.0. CodeIgniter 3.0 has its own test
code with PHPUnit, and the code coverage for those tests is around 60%. We are progressing a bit
day by day.
Have you ever written test code for your web application? If you haven’t, you may imagine that
writing test code will be very difficult or bothersome. Maybe you want to write test code, but don’t
know how to do so.
It is common to over-estimate the cost of learning something new, and testing is no exception. After
reading a tutorial for PHPUnit, I thought, “So how do I test my application?” I had trouble seeing
the similarities between the tests in the tutorial and the tests I would need to write for my own
application.
This book is a beginners’ guide for automated testing of PHP web applications. Of course, you will
be able to write test code for any PHP applications after reading this book, but the focus will be on
web applications.
I eschew complexity, favoring simple solutions. I use simple and easy to understand solutions first
in the book, so you won’t get lost. Let’s keep going!

The Book at a Glance


If you want to know about this book, this is a great place to start. What follows is a very quick
overview of what each chapter covers. This should give you an idea of what’s ahead, or serve as a
starting point if you want to find a particular portion of the content to review later.

Chapter 1: What is Automated Testing?

Let’s begin learning about automated testing. First we will explore the basic concepts of automated
testing. We will find out why and what you should test. At the same time, I will explain the ideas
and testing policies used by this book.

i
Preface ii

Chapter 2: Setting Up the Testing Environment

To run tests in your PHP environment, you will need to install some additional software. For this
book, this includes CodeIgniter, PHPUnit and a tool which acts as a bridge between them, ci-phpunit-
test. If you don’t like command line, you can use VisualPHPUnit to run tests via your web browser.

Chapter 3: Test Jargon

We define test jargon here. One of the annoying and confusing things in testing is the new
vocabulary required to understand it. By the end of this chapter we’ll help you understand
the difference between Unit, Integration, and System testing; Functional and Acceptance testing;
Fixtures and Mocks; and more.

Chapter 4: PHPUnit Basics

In this chapter, we will learn the basics of PHPUnit. We will run PHPUnit and learn how to configure
it. After that, we will study PHPUnit conventions and write our first test. We also cover PHPUnit
functionality, data providers, fixtures, and assertions.

Chapter 5: Testing a Simple MVC Application

You’ve already learned how to write test code, so here we will write tests for a CodeIgniter Tutorial
application. We will write tests for a controller and a model. In this chapter, we will use the database
for model testing.

Chapter 6: Unit Testing for Models

We will learn more about testing models. We will write tests for models without using the database.
To do this, we will learn about PHPUnit mock objects.

Chapter 7: Testing Controllers

We will learn more about testing controllers in this and the next two chapters. In this chapter, we
will write tests for a controller for reviewing, and write tests with mocking models. We also will
write test cases for authentication and redirects.

Chapter 8: Unit Testing CLI Controllers

We will continue learning to write tests for controllers. In this chapter, we will write unit tests for
controllers, and learn about monkey patching.

Chapter 9: Testing REST Controllers

In this chapter, we will learn about testing REST controllers. You will learn how to send (emulate)
requests with methods other than GET and POST.
Preface iii

Chapter 10: Browser Testing with Codeception

In previous chapters, we have been using PHPUnit. In this chapter, we will learn about another
testing tool. We will install Codeception, learn to configure it, and write tests which work with the
web browser.

What You Need for This Book


I assume you have a general understanding of PHP 5.4 and object-oriented programming (OOP),
and you have PHP 5.4, 5.5, or 5.6 installed.
If you know CodeIgniter, you may have an easier time with some parts of this book, but if you don’t
know it, don’t worry. CodeIgniter is an MVC framework that is very easy to learn and understand,
and it has great documentation. I will explain CodeIgniter-specific conventions and functionality in
this book.
I do not assume that you are using a specific operating system. However, my code examples are
written for Mac OS X. Bash commands are provided for Mac OS X and also work on Ubuntu. I have
not tested them on Windows, but they will probably work.
We use the following software in this book:

• PHP 5.5 (You can use PHP 5.4 or 5.6)


• CodeIgniter¹ 3.0
• ci-phpunit-test² 0.10
• PHPUnit³ 4.8
• Codeception⁴ 2.1
• Selenium Standalone Server⁵ 2.48

Who should read This Book?


This book is for PHP developers who don’t know Automated Testing or Unit Testing, or for those
looking for help testing CodeIgniter applications.
If one or more of the lines below sounds familiar, this book is perfect for you!

• I have never written test code.


• I want to write test code, but I don’t know how.
• I tried to write test code in the past, but I couldn’t quite figure it out.
¹http://www.codeigniter.com/
²http://kenjis.github.io/ci-phpunit-test/
³https://phpunit.de/
⁴http://codeception.com/
⁵http://www.seleniumhq.org/
Preface iv

Why PHPUnit?
PHPUnit is the de facto standard Testing Framework in the PHP world.
These popular PHP frameworks use PHPUnit for their own tests, and they provide support for
application testing with PHPUnit:

• CakePHP
• FuelPHP
• Laravel
• Symfony
• Yii
• Zend Framework

CodeIgniter 3.0 uses PHPUnit for testing its system code. Support for application testing with
PHPUnit is currently planned for CodeIgniter 4.0.

Is This a CodeIgniter Book?


This book is not specifcally for CodeIgniter, but we use CodeIgniter applications in our examples.
Probably 85% of the book’s content is not specific to CodeIgniter, and is applicable to testing any
PHP application.
So, if you want to learn Automated Testing in PHP, this book is still good for you. Most of the
techniques outlined in this book can be applied to any other PHP framework, and even to other
languages.
In modern web development, you probably use a framework. I don’t know what framework you use
or like, but if you learn testing with a framework, you can write test code more easily in your real
development environment.
CodeIgniter is one of the most easily understood frameworks currently available for PHP. This will
allow you to spend more of your time learning about testing, even if you don’t know CodeIgniter.
Another reason I chose CodeIgniter as the framework used in this book is that too many CodeIgniter
developers don’t write test code. So, I’m hoping that by choosing CodeIgniter for my examples, this
book will promote better testing practices in the CodeIgniter community.

Is Testing PHP Applications Difficult?


No, but you need the right tools and you need to know how to write tests.
Preface v

Is Testing CodeIgniter Applications Difficult?


No, at least it is not difficult with CodeIgniter 3.0.
Previously, it was said that testing CodeIgniter applications was difficult, but I will show you why
this is no longer the case.

Testing is Fun and Easy


Yes, it is really fun. Do you like to write code? Tests are also code. Good tests will help you write
better code.
When people are asked why they don’t write test code, it is often because they think it will be
difficult or will take too much time.
I will show you how to write tests and try to show you that it can be fun and easy. Writing good tests
now will help you catch mistakes earlier, and make it easier to change your code without introducing
errors, saving time in the long run.

Conventions Used in This Book


The following typographical conventions are used in this book:

• Italic: Indicates new terms or technical terms.


• Constant width: Used for program listings, as well as within paragraphs to refer to program
elements such as class or function names, variables, statements, and keywords. Also used for
Bash commands and their output.

For example, the following is a block of PHP code:

1 <?php
2
3 echo 'Hello World!';

Sometimes we use diff-style:


Preface vi

--- a/CodeIgniter/application/tests/libraries/Temperature_converter_test.php
+++ b/CodeIgniter/application/tests/libraries/Temperature_converter_test.php
@@ -6,7 +6,7 @@ class Temperature_converter_test extends TestCase
{
$obj = new Temperature_converter();
$actual = $obj->FtoC(100);
- $expected = 37.0;
+ $expected = 37.8;
$this->assertEquals($expected, $actual, '', 0.01);
}
}

The listing above is in a format called unified diff. It shows the difference between two files. The
format starts with two-line header, with the path and name of the original file preceded by ---
on the first line, and the new file preceded by +++ on the second line. In some situations, each line
could include a date/time stamp, as well.
In this case, the original file and the new file are the same file (this might not be the case if the file
was moved or renamed, or if the diff was to indicate that the content was moved to a new file).
Following this are one or more change hunks which show areas where the files differ.
The line “@@ -6,7 +6,7 @@” shows the hunk range. The first set of numbers (“-6,7”) indicates the
lines in the original file, the second set (“+6,7”) indicates the lines in the new file. These numbers
are in the format ‘start,count’, where the ‘,count’ may be omitted if the hunk only includes one
line. So, in this example, the hunk starts at line 6 in both files and contains 7 lines in both files.
The contents of the hunk (following the hunk range) contain the lines from the files, with additions
preceded with + (highlighted in green here), and deletions preceded with - (highlighted in red here).
The remaining lines (not preceded with either a - or +) are provided for context.
In short, remove the line(s) starting with - from the original file and add the line(s) starting with
+ to get the new file.

This is an example of a Bash command and its output:

$ echo 'Hello World!'


Hello World!

This is an example of a note or general information.

This is an example of a tip or suggestion.


Preface vii

This is an example of a warning or caution.

This is an example of an exercise.

Errata
Although I have taken care to ensure the accuracy of this content, mistakes do happen. If you notice
any mistakes, I would be grateful if you would report them to me. If you find any errata, please file
an issue on GitHub https://github.com/kenjis/codeigniter-testing-guide, and I will update the book
as soon as possible.
1. What is Automated Testing?
Welcome to the testing world!
In this chapter, we will learn about the concept of automated testing and learn why and what you
should test. As we go, we will begin to develop the testing strategy which will be applied by this
book.

1.1 Primitive Example


We will begin with a very simple example, a function which returns 'Hello World!'. For this
example, we’ll place the function in a file called hello.php in a location easily accessible to our
server.

hello.php

1 <?php
2
3 function hello()
4 {
5 return 'Hello World!';
6 }

How do we test this function?

Exercise
At this point, please stop and think about how you would test this function.

Manual Testing
We’ll start with a manual test, printing the result of the function in a page viewed by your web
browser. We’ll place this function in another file, called hello_test_with_your_eyes.php in the
same location as the hello.php file which holds our hello() function.

1
What is Automated Testing? 2

hello_test_with_your_eyes.php

1 <?php
2
3 require __DIR__ . '/hello.php';
4
5 echo hello();

If you navigate to hello_test_with_your_eyes.php in your browser and see Hello World!, the
function and the test both work fine.
Alternatively, you can just run it from PHP’s Command Line Interface (CLI):

$ php hello_test_with_your_eyes.php
Hello World!

This is manual testing.


All PHP developers have tested like this at some point. Manual testing with your web browser is
very common. You write some code expecting a certain outcome, then you run the code to verify
that you receive the expected outcome. If you look at the web page you built to verify you aren’t
receiving errors and the outcome looks more or less as you expect, you are already testing your
application.
However, if you test your application by yourself, and by manually checking every possible action
the user might take, it could take some time to test. If your application is very big, testing every
possibility in the entire application could take a very long time, which means you can’t possibly test
everything very often.

Automated Testing
What if, instead of manually checking the results in a web browser, you write code to test your
application? The following is some very primitive test code for our primitive hello.php application.
We would place this code in a file called hello_test_automated.php alongside our application and
our manual test.
What is Automated Testing? 3

hello_test_automated.php
1 <?php
2
3 error_reporting(-1);
4
5 require __DIR__ . '/hello.php';
6
7 function assertTrue($condition)
8 {
9 if (! $condition) {
10 throw new Exception('Assertion failed.');
11 }
12 }
13
14 $actual = hello();
15 $expected = 'Hello World!';
16 assertTrue($expected === $actual);

If you run this code, you probably won’t see anything, unless the hello() function returns
something unexpected, in which case you will receive a fatal PHP error and a stack trace.

If our hello() function does not return 'Hello World!', our test will fail. Since the code verifies
that the result of executing the function matches the expected result, rather than having to verify
the result in a browser (or in the CLI) for ourselves, we call this automated testing. Using automated
tests, you could run the test code every time you make a change, or at a certain time every day,
because it is PHP code!
When writing an automated test, you think of what you would do to test the code by hand or how
you might confirm the code is working properly, then write code which will do the testing for you.
In the long run, this means you can spend less time manually testing your code, and it will protect
your code base from unexpected changes.
Automated testing has two features:

• it is very fast,
• so you can run tests very often.

Testing Tip: Avoid Slow Tests


Speed is the one of the most important things in testing. If you have slow tests, they prevent
you from testing. If you find that one or more of your tests is slow, you should probably
try to speed it up.
What is Automated Testing? 4

This example is simple, so you might think the test is nonsense. However, if you expect a certain
output given a certain input, the complexity of the function you are testing has very little impact on
the complexity of the test, so even very complicated functions might have tests with code which is
similar to the test we have created for our primitive hello function.

1.2 Why should you write test code?


You don’t have to write test code, but even if you choose not to, it is better that you know how to
write it. Thinking about how you would write a test for your code makes you consider how your
code might fail and what expectations you have for a given piece of code.
According to “Top 12 Reasons to Write Unit Tests¹,” you will get the following benefits when you
write test code:

1. Tests Reduce Bugs in New Features


2. Tests Reduce Bugs in Existing Features
3. Tests Are Good Documentation
4. Tests Reduce the Cost of Change
5. Tests Improve Design
6. Tests Allow Refactoring
7. Tests Constrain Features
8. Tests Defend Against Other Programmers
9. Testing Is Fun
10. Testing Forces You to Slow Down and Think
11. Testing Makes Development Faster
12. Tests Reduce Fear

In my opinion, the most important thing is reducing fear. If we have well-tested code, we can change
and improve it without fear that we might break existing code.

1.3 Finding the Middle Way


Have you ever heard about the right way to write unit tests?

• Don’t access the database.


• Don’t use new operators (use dependency injection and factories).
• Rewrite your code to be more testable.
• Do not interact with the file system, use a virtual file system instead.
¹http://www.onjava.com/pub/a/onjava/2003/04/02/javaxpckbk.html
Random documents with unrelated
content Scribd suggests to you:
Greek myths​—Z ​ eus and his character​—​
Prometheus and Faust​—T ​ he nine muses and
their leader​—​Greek life a continuous festivity​
—​Greek poetry and philosophy​—​Greek
artistic development​—T ​ he Olympian,
Pythian, Nemæan, and Isthmian games​—​
Greek architecture: the temple​—​Building
materials​—S​ ite of temples​—​Proportion​—​Plan
of temples​—T ​ he Doric, Ionic, and Korinthian
orders and their subdivisions​—T ​ he Attic style​
—​Greek pottery and Greek sculpture​—​
Different periods​—T ​ he British Museum and
Greek art​—​Onatas, Ageladas, Kalamis,
Pheidias, Praxiteles, Skopas, and Lysippus​—​
The Parthenon​—A ​ phrodite no longer draped​
—​The groups of Niobe, Laokoön, and the
Farnese bull​—​Causes of the decline of Greek
art

CHAPTER IX.
ETRUSKAN ART.
The first settlers in Etruria​—T
​ heir gods of the
first and second orders​—T ​ he ritual of
thunder​—T​ emples and tombs​—S ​ ubdivision of
tombs​—​Cinerary chests​—​Excavations at
Præneste​—​Pottery and metal works​—T ​ heir
style either Archaic or Etruskan​—​Division of
Etruskan works of art into five principal
categories 212

CHAPTER X.
ROMAN ART.
Characteristic differences between Greeks and
Romans​—T ​ he triple theocracy of Rome​—T ​ he
mythical period of the seven kings of Rome​
—​Rome as republic​—​Roman mythology​—​
Rome under the emperors​—​Roman public
games​—​Roman literature the outgrowth of
Greek literature​—​Polylithic wall decorations​—​
The arch, cross-vault, and cupola​—​Periods of
Roman art and their subdivisions​—T ​ emples​—​
Fora and theatres​—T ​ he mausoleum of
Augustus​—​Hadrian, the divine architect​—​
Triumphal arches​—T ​ he baths of Caracalla​—​
The advent of Christianity 228

CHAPTER XI.
EARLY CHRISTIAN ART.
North and south of our globe​—​Buddhism and
Christianity​—​Christ’s divine teachings​—​
Romanesque and Byzantine art-forms​—​
Symbols, allegories, emblems, and myths​—​
Catacombs at Rome and Naples​—T ​ he
sacredness of the number seven​—​Christian
art in its essence and different phases​—T ​ he
spiritual element predominates​—T ​ he first
Christian churches​—​Constantine​—​Ravenna
and its early churches​—S ​ t. Sophia in the
Byzantine style​—​Migration of northern
nations​—T​ heir religious notions​—T
​ he
Teutons turn Christians​—W ​ ood and ivory
carvings​—A ​ rt in its relation to the
progressive development of mankind​—​
Summary and conclusion 264
Bibliography for the study of the historical
development of Art 301

Index 305
MANUAL
OF THE

HISTORICAL DEVELOPMENT OF
ART
CHAPTER I.
PROLEGOMENA.

Gazing at the heavens on a starry night, we see, in addition to


myriads of sparkling worlds floating in the air, a great quantity of
nebulæ—either decayed systems of worlds, or worlds in formation.
Worlds which have lost their centre of gravity and fallen to pieces; or
worlds which are seeking, according to the general law of
gravitation, to form a central body by the attraction of cosmical
ether. The one phenomenon is that of destruction, the other that of
new formation.
This double process is continually repeating itself in the
development of art. Consciously or unconsciously, the artists of the
different nations, at different periods, devote themselves to the
dissolution or reconstruction of artistic products. To become
acquainted with this process, to trace the elements from which art is
built up, or the influences which engender a dissolution of artistic
forms, is of the greatest importance.
Art must be looked upon as the phenomenal result of certain
religious, social, intellectual, and natural conditions. To trace these
conditions, their origin, influence, and gradual development, by
means of a critical and historical investigation into the causes which
produced them, will be our task. For art is like a mirror: whatever
looks into it is reflected by it. If a poor, untrained imagination stares
into it, no one must be astonished that poor and distorted images
result.
It is usually accepted as a truism that the essence of art is the
reproduction of nature. Wherever, then, nature were reflected in the
‘Art-mirror,’ we should have the best work of art. But this is not so.
For art has to reflect the phenomena of the makrokosm as a
subjectively-conceived mikrokosm. We do not see matters as they
really are, as each thing is surrounded by a thick fog of incidental,
objective, and subjective peculiarities. This fog must be cleared
away, to show us nature in the bright colours of intellectual and self-
conscious idealisation.
Nature furnishes us with mortar and stones for the building, but
the architect’s intellectual power has to arrange these elements, and
to bring them into an artistic shape. Nature furnishes us with
flowers, trees, animals and men; but the ornamental designer or
painter has to reproduce and to group them so as to impress the
forms of nature with an intellectual vitality.
Before the artist proceeds to his work he must become
thoroughly conscious of the distinction between the SUBLIME and the
BEAUTIFUL. It is essential that he should draw a strict line of
demarcation between the two conceptions; in order not to waste his
energies on the reproduction of objects which are beyond the
powers of art.
During the long period of the cosmical formation of the earth,
when mountains were towered upon mountains, rocks upheaved,
islands submerged; when air, water, fire, and solid matter seemed
engaged in never-ending conflict—nature was sublime. The dynamic
force appeared to be the only element, and the counterbalancing
static force was without influence. Gradually vegetable and animal
life, in their first crude forms, commenced to show themselves.
Zoophites were developed into megatheriums and mastodons.
Mammoths and elks sported on plains which now form the mountain
tops of our continents. Scarcely visible coral animals were still
engaged in constructing mountain chains, and a luxuriant vegetation
covered the small continents. Such transformations, convulsions, and
changes are gigantic, grand, awe-inspiring—sublime, but not
beautiful. Whenever nature is at work, disturbing the air with electric
currents or shaking huge mountains, so that they bow their lofty
summits, or when the dry soil is rent asunder, and sends forth
streams of glowing lava, we are in the presence of the sublime, not
of the beautiful. Whenever man’s nature is overawed, whenever he
is made to feel his impotence by the phenomena of nature, he faces
the sublime. In art, only a few divinely-gifted and chosen geniuses
have ever reached the sublime.
When, however, the cosmical forces had expended their
exuberant powers—when a diversified climate had produced those
plants and animals that surround us—when man appeared on this
revolving planet, and by degrees reached self-consciousness as his
highest development—then only beauty acquired existence and
dominion on earth. Without men capable of understanding what is
beautiful, art would have no meaning.
The aim of science is to vanquish error; the province of industry
to subdue matter, and the vocation of art to produce beauty. The
artist must not neglect science, for he has to be truthful, as error is
ugly; he must make himself well acquainted with matter, for he has
to use, to transform, and to modify it; and, finally, he has to hallow
this scientifically-treated matter by impressing it with the stamp of
ideal beauty.
The attainment of this, the perfection of art, has been slow and
gradual. Though art, like all the inventions, took its origin in want
and necessity, the utilitarian spirit is the very bane of art, for art
flourishes only under the influence of the very highest intellectual
culture.
Nature produces like art; but the products of nature are the
unconscious effects of the immutable law of causation. The products
of art are the results of the conscious intellectual power of the artist.
It is the free, yet well-regulated, consciousness of the artist that
elevates his productions into works of art. Undoubtedly the great
store-house of the artist is nature; he learns from nature how to
ornament, but he has to discern, to combine, to adapt, to select, his
forms. The whole success of the artist, in whatever branch he works,
must depend on an earnest and severe use of the word CHOICE.
‘He is truly great who knows the value of everything, and
distinguishes what is more or less great, and what is most estimable,
so as to begin from that, and to apply the genius, and fix the desires
upon the execution of things worthy and great.’ This mode of
thinking was followed by the most celebrated and enlightened artists
from the ancient Greeks to our own time. They knew to distinguish
that which was most worthy in nature, and to this they directed their
study, diligence, and industry. Inferior geniuses, because they are
attached to mediocrity, believe that a mere clinging to nature
constitutes all art; and the lowest artists are enchanted with the
minutiæ of little works, taking them for principal things; so that
human ignorance passes from the trifling to the useless, from the
useless to the ugly, and from the ugly to the false and chimerical.
In treating of the historical development of art, to enable artists
to distinguish and to choose the best, and not only to imitate but to
create consciously for themselves, it is necessary to make them
theoretically acquainted with the progress of art.
To trace historically the changes art had to undergo is necessary
for all really self-conscious artists. Art with us is still looked upon as
entirely subject to individual taste. Everyone thinks himself
competent to have an opinion on products of art. ‘De gustibus non
est disputandum’ is heard not only in our drawing-rooms, but also in
art-circles. This false and utterly untenable adage is the cause of the
chaotic anarchy in our art-world.
So little as there can be differences in truth, can there be
differences in beauty. It is the duty of philosophy to strive for truth;
it is the task of the theoretical artist to point out what is beautiful.
We may treat art from three different points of view:—
1. From a realistic point of view, taking nature and geometry as
its basis.
2. From an historical point of view; showing by antiquarian and
archæological researches its gradual development.
3. From a critical point of view; propounding abstract principles
of speculative philosophy and esthetics as applied to art.

A.
The realistic school has in later years had an immense influence
with us. Art-critics have almost gone so far as to demand from the
artist a correct rendering of the very stratification of rocks; or of the
different kinds of soil, to such a degree that the farmer should be
able to recognise the ground in which to sow oats or wheat.
Pictures, according to these estheticists, should be geological maps,
mineralogical collections, and, so far as flowers are concerned,
perfect herbariums. When this school takes up the archæological
view, it clings with indomitable tenacity to given forms, and checks
imagination. Art is then only to be handled as the Greeks or Romans
practised it. Either the Gothic or the Renaissance style is to be
slavishly imitated. This school has one great drawback: it considers
all things natural beautiful, and looks upon an imitation of that which
was as better than an exertion of the self-creative originality of the
artist.

B.
The historical school endeavours to bring before our eyes the
past, so as to enable us to understand the present, and to influence
the future of art. This school has followed two divergent directions,
the Antique and the Gothic, the classical or romantic; the one
holding that everything beautiful must be based upon Greek
patterns; the other that all beauty is confined to the Gothic. The
writers of these two schools bewilder the students; either driving
them into a cold, soulless imitation of classic forms, or forcing them
to sacrifice everything to trefoils, pinnacles, tracery, finials,
buttresses, thin spires, painted windows, and pointed arches.

C.
The critical school indulges in tall phrases, mere hypothetical
paradoxes, often startling the world with speculations of the wildest
sort. Art-critics frequently roam in the spheres of surmises; they
have their good points, but often neglect reality, or the historical
ground; they sacrifice everything to the idea, which is with them the
only productive basis of everything existing in art.
We shall try to be realistic, as it would be vain to attempt to
detach art from the influences of nature; for art borrows its principal
elements from the impressions of natural phenomena. We shall be
historical, and point out the progressive development of art; and,
lastly, we shall endeavour to be critical. Speculative philosophy has
its merits in art. Esthetical criticism suggests new ideas, and new
ideas engender new forms. We shall endeavour to adopt from each
of the three schools what is best. Our age is an age of eclecticism in
art. We must, however, try to prepare for a period of original vitality,
which can only be done by avoiding one-sidedness and heedless
originality. We shall try to suggest and to excite in our readers new
thoughts. As music speaks in sounds, poetry in words, so art in
forms; but music, poetry, and art are subject to certain rules, without
which harmony would become dissonance, poetry an inflated prose,
and art a tasteless entity, of which quaintness will be the only
distinguishing attribute. What we call our sense of beauty is based
on those laws which make the existence of the universe possible.
The Greeks used for beauty in art the same word, as for order, or
the perfect arrangement of the universe. The word κόσμος {kosmos}
(from which we have ‘cosmetic,’ any beautifying application) may
teach us how we should look upon works of art, which ought to be a
reflection of the general laws ruling nature.
Two forces guide our material and intellectual life. We possess
two means of acquiring knowledge and of practising art: reason and
experience. Impressions from without are the everlasting source of
all our conceptions. Hunger and thirst drive us to seek nourishment,
to become fishers, hunters, herdsmen, or agriculturists. Cold and
heat force us to seek a shelter, to construct wigwams, huts,
dwellings on piles, cottages, houses, palaces, and temples.
Though order and harmony prevail in the outer world, every
atom of the universe is endowed with an unconscious will or life of
its own. Atoms seek atoms according to inherent laws, or fly from or
annihilate one another. The whole process of life around us appears
to be one never-ending struggle. Apparently there rules only the law
of chance and might; what cannot conquer is conquered.
History is one long catalogue of appearing and disappearing
nations, of devouring and devoured kingdoms and empires. It is as
though generation after generation had emerged from the spectral
past into the sanguinary present, to destroy or to be destroyed. This
conflict in the outer world is seconded by everlasting conflicts in our
inner world. Fear, hope, love—passions of all kinds, imagination and
reality, ignorance and knowledge, pride and humility, prejudice and
wisdom, form an intellectual hurricane not less destructive than the
warfare of the cosmical elements. Religion, Science, and Art, this
divine triad, step in. Religion excites in us the hope of higher and
better morals; science creates consciousness of the laws according
to which we are governed; the link between cause and effect is
traced, and the rule of arbitrary chance narrowed. Lastly, art throws
its beautifying halo on everything. Thus these three are instrumental
in elevating our mind, expanding our intellectual powers, and
bringing harmony and beauty into the eternal conflict. Faith is the
element of religion, experience the element of knowledge, and
beauty the element of art. Whilst faith and experience are possible
without an artistic elevation of the mind, art must combine the
elements of religion and science, and form through beauty a visible
link between these elements.
The sublime, as we have said, rules in the universe. Clouds
chase one another and are subject to everlasting changes. Trees
cover the surface of our globe, forming woods at random. Mountains
are towered up, as if hurled together by chance. Seas form a
bewildering variety of coasts. Streams wind their paths through
mountains and valleys with capricious irregularity. All these
phenomena confuse and oppress us, they engender an
incomprehensible, indistinct feeling in us. But so soon as we begin
with our intellectual force to sift, to separate, and to detach single
phenomena from the general mass—as soon as choice begins to
work, the isolated phenomenon displays at once its symmetrical
beauty.

This is the case with crystallisations, the first artistic products of


unconscious nature. If we look at a vast plain covered with snow, a
feeling of sublime cold and wretchedness overcomes us; but if we
take up one isolated snow-flake, and place it under a microscope, we
find that the elements of the crystallised drop of water surround with
harmonious regularity a common centre, which is the body, from
which radiate as integral parts the diversified forms of the flake. In
studying snow-flakes, we find that the three dimensions of space—
height, breadth, and depth, limited by symmetry, proportion and
direction—are the principal elements of every form which in itself has
to represent a detached total. In all the crystallisations there is one
‘momentum’ of formation—the centre, from which all the parts
emanate perfectly well-balanced and complete in themselves. The
elements of which all artistic works, whether natural or produced by
men, are composed, are the straight line and the waving line. With
these elements we can obtain the three principal conditions of every
work of art—symmetry, proportion, and direction. Snow-flakes may
be used in any direction, and therefore they may be set down as
without distinct direction. The rays with their radiation, however, are
formed according to the principal law of the universe. They represent
the dynamic force; they strive at isolation from the centre which
must be looked upon as their static momentum. Thus in the first
artistic products of nature positive and negative, or rather dynamic
and static forces are clearly perceptible. The horizontal line is the
representative of the static, whilst the vertical line is the indicator of
the dynamic force.
Symmetry is a perfect equality of form to the right and left of a
vertical line on a horizontal base.
Eurythmy consists in a repetition of variegated forms.
In order to produce eurythmy we must confine symmetry within
a certain compass; for this purpose we have the frame. Our doors
are nothing but frames for the entering or departing individuals; as
our windows are frames for the landscape, sky, or walls on which we
look, or for ourselves when seen from without. The frame, whether it
be real or imaginary, as the correct limitation of forms, is of the very
highest importance in decorative and pictorial art.
Eurythmy may be alternating. This alternating principle is
observed in metopes and triglyphs. The alternation may be
interrupted by a cæsura (a mark or sign of rest). Masks, heads of
lions, or any other figures may form the cæsura, as decorative
elements in the long lines of the tops of houses, palaces, or temples.
The cæsura, combined with eurythmy and symmetry, will give us the
best patterns for flat decorations, as in carpets, paper-hangings,
keramic works and metal or wood ornaments.
Applying what we have said of crystallisations to plants and
animals, we find that symmetry is undoubtedly the predominant
element in every flower. The plant developes itself from the ground,
which is its horizontal basis. It shoots up generally in a vertical
direction, as a radiation from our globe. In trees the branches,
leaves, flowers, and fruits are clustered around a central line in
eurythmical proportion. In flowers symmetry predominates, whilst in
trees eurythmy prevails. In considering the branches of a tree in
relation to its trunk, we find the same symmetry and eurythmy,
though the direction be changed. We can study these forms best in
plants of the coal formation—the Sigillaria, Stigmaria, Lepidodendra,
and Calamites; and in ferns, fir-trees, cedars, &c.
In the palm tree we see most distinctly the working of the
conflicting forces of nature. The dynamic force of vitality drives the
stem upwards, and the static force of gravitation towards a common
centre is expressed in the beautifully-drooping curves of the leaves.
Symmetry is further to be observed in the lowest animals, in polyps,
radiata, &c., but never in higher species, in which it is not
planimetrical (viz., cannot be treated on a plane) but linear, none of
them being perfectly regular in any of the three dimensions of space.
Man is altogether different from the products of the mineral or
vegetable kingdoms, which give us the prototypes of conventional
art. Man is not in all directions symmetrical in the strict sense of the
word. He has not two heads, two noses, or two mouths. The
component elements in man are different. His very nature revolts
against a planimetrical treatment. This was perfectly understood by
the masters of arabesque, who have always turned man half into a
fish, a plant, a serpent, a tendril, or some other form adapted for
planimetrical treatment. Eurythmy and Proportion are the elements
of higher organic forms—to which must be added direction or Action,
and finally Expression.
In most of the lower animals the vertebræ are horizontal, and
coincident with the moving direction of the whole creature. In man,
on the other hand, the vertebræ are vertical, in opposition to the
moving direction which is horizontal; so that the vertebræ and line of
motion are at right angles.
In men, detached as they are from their horizontal basis, the soil
—carrying their static force with them, and able to change it either
from below, upwards, or from front to back—direction is of a
complicated nature, and must be well studied, so as not to produce
incongruities.
If a woman or man were painted with the most beautiful and
expressive face, but having it twisted round, so as to crown the
spine, we should turn from it with disgust, as anyone endowed with
the sense of beauty turns from acrobats, because the natural laws of
gravitation and symmetry would be violated. This illustration may
serve to prove, that there are laws in art with which we must make
ourselves acquainted, and that the mere ‘right of taste,’ in the
general sense of the words, cannot promote the understanding and
appreciation of our artistic productions.
Next to direction we have to take into account motion. This
element is in animals and men produced by their inherent dynamic
force, counteracted by the body itself, which represents the static
force, or the ‘vis inertiæ,’ chaining them to the centre of gravitation
in the earth.
Motion again leads to expression and action.
Expression is the effect of the conflicting static or dynamic
(passive or active) state of the mind, so far as this state is revealed
in the lineaments of the face.
Action is the effect of the same conflicting force so far as it is
expressed in the limbs and the position of the body.
A third force, which is often used unconsciously, necessarily
grows out of these elements—the controlling or ruling element, or, as
Vitruvius has it, ‘the principle of authority.’ This element points out
the preponderance of certain forms as the visible representatives of
the general principles which we have stated, bringing into the variety
of details, harmony and unity. This controlling element stands to the
surrounding and united parts in the same relation as the key-note to
a harmonious melody. Without that key-note no harmony—without
the controlling element no beauty, were possible.
Having proceeded step by step from the formation of matter in
crystals to man, we may set down the following as the five principal
elements necessary to beauty in art:—
1. Symmetry.
2. Eurythmy.
3. Proportion.
4. Direction or motion.
5. Expression.
α. Symmetry has already been amply treated.
β. Eurythmy is either stereometric or planimetric. It is
stereometric in balls and in regular solid bodies, such as the
tetrahedron, a figure of four equal triangular faces, or the
polyhedron, a figure with many sides. These forms are symmetrical
without any controlling element. Such an element shows itself first in
the ellipsoid—distinct from the oval—in the prism, and the pyramid.
Planimetric eurythmy preponderates in snow-crystals, flowers,
plants, trees, and the lowest animals.
The controlling element shows itself in the grouping of the single
parts round a common centre, which is often distinguished by a
contrast in forms or colours. It is unconsciously expressed by a sign
or mark.
Ornamentation takes its origin in the effort to express, to
designate, or to mark out the controlling element. The ornamented
object has only then a meaning, when it expresses visibly the hidden
idea of the controlling element, say the idea of fastening or keeping
together, as in clasps, brooches, buckles; or the idea of equilibrium,
as in earrings. Such signs or marks were very early used, and are
spread all over our globe; they developed into the rough tombs in
Phrygia, Greece and Italy; took a higher form in Central America and
Assyria; became crystallised in the Pyramids; and attained the
highest perfection in the tombs of Mausolus, Augustus, and Hadrian.
The mark or sign is also used in games, as on race-courses, in the
stadium, the circus, or the amphitheatre. A more distinct expression
is gained when the mark or sign, as divine statue, altar, &c., is
surrounded by rhythmically-arranged circles or encompassing walls,
as the visible expression of the union of the many, or variety, for one
religious or ceremonial purpose. The mark or sign reflects, on the
one hand, the idea of harmony, whilst, on the other, the
rhythmically-arranged surroundings form an impressive total,
heightening the force of the controlling element. This law explains
the awe, veneration, mysterious feeling, and secret fear with which
men at all times have looked upon the central mark or sign, whether
in the simple stone-circles of Abury, Stonehenge, and Carnac, the
rock-hewn temples of India, the temples of Egypt, Greece, and
Rome, or the synagogues and churches of our own times.
Next to the controlling element, we must take into consideration
the grouping of the whole object on a horizontal basis around a
vertical axis. This axis becomes the seat of the linear, symmetrical,
controlling element. It is especially marked by richly ornamented
reliefs or by gaudier colours, so pronounced that the other parts of
the ornamented object appear as mere accompaniments of the
horizontal and vertical lines. Remarkable in their incongruity, but
often unsurpassed in the application of this principle, are the
tattooed heads of savages, in which the linear central line is
ornamented symmetrically on both sides of the face—the prominent
parts being marked by spirals to make them appear still more
prominent.
γ. Proportion, as an element of art, cannot work by itself, but
must be considered in relation to its parts and the controlling
element. Proportion consists of a basis, a middle piece, and a
dominant. To illustrate this, we have in plants and trees, the root
(basis), the stem or trunk (middle piece), and the top, crown or
flower (dominant).
The basis represents the cosmical element of gravitation by
powerful masses, simplicity of forms, and dark colouring. This law
was especially observed in the excellent decoration of the Roman
houses at Pompeii, and is still followed in our wainscoting. We try
unconsciously to express the static force from which the dynamic
rises.
The middle piece, growing out of the basis, is supported and
supporting; it unites the elements of the basis with the top or
dominant; it is the connecting link between these two extremes. The
basis stands in the same relation to the middle piece, as the latter to
the dominant.
The dominant harmoniously reconciles the conflicting forces of
striving upwards, and being drawn downwards. Variations in these
relations are not only allowable, but form the very element of the
artist’s creative originality—so long as he clearly marks the purpose
of the three elements.
δ. Direction, or motion, in its highest form is only to be found in
man. In fishes the axis, or seat of the controlling element, is not
fixed as in plants. If fishes pursue some point of attraction, they
shoot forward in a straight line, so that a conflict between the static
and dynamic forces is never visible in them, because the axes of
these two forces are always one and the same. This is entirely
different with birds, quadrupeds, and especially with men, who, to a
great extent, are masters of their motions; for will, as the force of
their conscious intellect, changes their static as well as their dynamic
direction.
Man is the symbol of earthly perfection. In him all laws and
elements of the universe are united. What is with inanimate nature a
static point of attraction, is with man moral; the dynamic force of
activity, is with him intellect. Animals also work, but their works are
in general the result of their instinct; whilst with man, though he
may also be ruled by unconscious impulses, intellect—self-conscious
intellect—is the mainspring of all his actions. These have a reflecting
mirror in the glance of his eyes, whilst the changing and changeable
effects of scorn, love, wrath, delight, happiness, or despair are
pictured in the mysteriously-woven lineaments of his countenance.
ε. Expression, of intellectual and moral impressions, is most
concentrated in MAN.
CHAPTER II.
ETHNOLOGY IN ITS BEARING ON ART.

Man is placed on this globe as a radius,—a detached radius. The


axis of his body is part of the diameter of the earth, and divides him
into symmetrical halves. A line, that passes at an equal distance
through the double organs, also divides the single ones into two
equally-arranged portions. We possess two eyes, to receive the
impression of light; two ears, to be touched simultaneously by the
waves of sound; two tubes are opened, to receive the refined,
imponderable bodies producing odour; the lips are grouped round a
marked central line to the chin. We have two shoulders, two arms,
two hands, two legs, two feet; both hands have the same number of
fingers, and both feet the same number of toes. On the other hand,
the parts, taken by themselves, break through all the laws of
symmetrical uniformity. The arms are longer than the trunk; the legs
are longer than the arms; hands end in unequally-subdivided fingers;
feet in similarly-treated toes. But notwithstanding this want of
symmetry there is perfect harmony in the relations of the parts to
the whole, so that man may be said to be the very master-piece of
creation. In considering the controlling linear elements, in the three
grand groups into which humanity may be best divided for a
comprehensive study of art, we find that the very fundamental facial
lines differ.
I.
We have first the Negro, the fossil, the black, or antediluvian
man. The eyes, nostrils, and lips are drawn downwards in
melancholy lines. He is cross-toothed (prognathous), triangular-
headed, has flat feet, long heels, an imperfect pelvis, but a very
powerful digestive organ, and a correspondingly enormous mouth.
The Oceanic Negro is the best example of this
group. He is slow of temperament, unskilled, his
mechanical ingenuity being that of a child; he never
goes beyond geometrical ornamentation; builds tumuli
or triangular wigwams; lives on what he finds by
chance, and, at the best, hunts or fishes. His reasoning
faculty is very limited, his imagination slow, but his
perceptive faculties (the senses) are highly developed. He is
altogether incapable of rising from a fact to a principle. He cannot
create beauty, for he is indifferent to any ideal conception. He
possesses only from 75–83½ cubic inches of brain, his facial angle
being about 85½ degrees. This lowest group of mankind branches
off into different types. The general features of the group have
neither changed nor improved. The Negro is still the woolly-headed,
animal-faced being, represented on the tombs of the Pharaohs,
because his bodily structure, his facial lines have not altered during
thousands of years. In studying the artistic products, the customs
and manners of this group, we can picture to ourselves the state in
which Asiatics and Europeans must have lived during the oldest
stone period. The Negroes use the same kind of flint instruments,
manufacture the same crude kind of pottery, adorn their clubs,
paddles, and the cross-beams of their huts with the same rope and
serpent-like entangled windings and twistings, that are found in
various parts of the globe of pre-historic times. The ruling lines of
the face and head of the Negro are reflected in his triangular or
mound-like architectural constructions.
II.
Next we have the Turanian (from tura, ‘swiftness of
a horse’), the Mongol, the square or short-headed
(brachikephalous), the traditionary, the yellow man. His
face is flat, his nose deeply sunken between his
prominent cheeks; his reasoning faculty is developed
only to a certain degree. He has small, oblique eyes,
the lines being turned upwards, expressing cunning and
jocularity. His mouth is less powerful than that of the negro. He has
broad shoulders, an expansive chest, thin and small bow legs, as if
formed to use those of horses instead of his own; he is an excellent
rider, but a slow though steady walker. He looks on nature with a
nomadic shepherd’s eye, and not with that of a settled artist. He
excels in technical ability, has great powers of imitation, can produce
geometrical ornamentation of the most complicated and ingenious
character, and a realistic imitation of flowers, butterflies, and birds,
but has no sense for perspective and no talent for shading. He is
incapable of drawing the human form. Sculpture of a higher kind is
unknown to him, though he can execute perfectly marvellous
carvings, which, though quaint in design and composition, are
wanting in proportion and expression. Faithful to his nomadic
traditions, and the lines of his head and face, his architectural
constructions take an according form. Like his facial lines, the roofs
of his houses are twisted upwards.
The amount of brain in the Turanian averages 83½ cubic inches,
and his facial angle is 87½ degrees.

III.
Finally we have the Aryan, the long or oval-headed man
(dolichokephalous), the historical, the white man, the crowning
product of the cosmical forces of nature. His facial lines are
composed of the two conflicting elements, the
horizontal and the vertical line, and are framed in by an
oval. His amount of brain is on an average 92 cubic
inches, and his facial angle 90 degrees. His
development is not limited. This group of mankind,
though divided into many different types (races or
nations), which have arisen from an intermixture with
the other two groups, or through the influences of climate, food, and
the aspect of nature, stands at the highest point of civilisation. As
the lines of his face are admirably counterbalanced, and his body is a
master-piece of regularity and proportion, he has tried to establish a
perfect balance between the conflicting forces in his moral and
intellectual nature. To him exclusively we owe art in its highest
sense. Once he stood on the same level with the primitive black
savage, then he advanced to the ingenuity of the yellow man, and
left both far behind him in his gradual but always progressive
development. He surpasses the other two groups of humanity, not
only in technical skill, but especially in inventive and reasoning
power, critical discernment, and purity of artistic taste. The white
man alone, has produced idealised master-pieces in sculpture and
painting.
The white man in his architecture uses either the horizontal or
the vertical line, or both; he takes the triangular building of the
negro and places it on the square tent of the yellow man, making his
house as perfect as possible; he goes further, and, in accordance
with his powerfully-arched brow, over-arches not only rivers and
chasms, but builds his magnificent cupolas and pointed arches, the
acme of architectural forms.
Ethnology then serves us as a foundation for the study of art in
its different phases.
Conforming to the general tendency of modern science, we have
tried to express the cause of the artistic development of the three
groups of humanity by figures; we have measured the seat and
instrument of our intellectual faculty, and have thus tried to leave the
sphere of mere conjecture, or unfounded opinion, in order to place
the phenomena of art-history on a firm basis. Though art,
undoubtedly, belongs ‘to the magic circle of the imagination, and the
inner powers of the mind,’ those powers are dependent on our very
bodily construction, the amount of brain and the facial angle. We do
not deal in mere hypothesis, but submit to our readers a complete
theory borne out by facts.
In considering the frontispiece of our manual, representing the
‘Tree of Art,’ we can visibly trace the slow and gradual development
of the white man. The negro fixes our attention only as savage; the
yellow man has a line of his own, and has remained stationary in his
artistic development; the white man has passed through the savage
stages, and by his own exertions, undergoing various phases of rise
and decline (the real signs of historical vitality), has steadily
progressed till he began to attempt, and to succeed in bringing
about, ‘a harmonious connection between the representation of
nature and the expression of awakened emotion, and a mysterious
analogy between the emotions of his mind and the phenomena
perceived by his senses.’
As all phenomena must take place in space and time (the two
fundamental forms of all existence), the products of art must also
have been executed under these two conditions, and can therefore
be treated historically.
Space is the expansion and extension of the forces of nature into
the infinite. Time is the limitation of this activity. Without space no
object could arrive at completion. Without time the subject would be
eternal. These are the two counteracting elements. The one, space,
is positive—the other, time, negative. Time is either relative or
absolute. If relative, it can be measured by an ascertained
succession of events. If absolute, it becomes measurable by years.
In both we can trace a gradual and successive development of
artistic forms. In general, time relative, with its succession of
products, is more reliable than time labelled with voluntary and more
than doubtful dates. For instance, we cannot measure the periods of
the formation of the earth’s crust by years, and still we are perfectly
convinced that the tertiary formation could not have taken place
before the primary; thus we are justified in assuming that the iron
period must have succeeded the stone or bronze period; bronze
instruments never being found with iron handles, whilst iron blades
have ornamented wooden or bronze handles. Man naturally scarcely
ever uses the worse material for a practical purpose when he has
once found a better one; but he will use the softer material as a
means of ornamentation.
That we have plenty of ‘survivals’ in art, as well as in nature,
does not in any way militate against the strict logic of facts. The
lowest forms of animals have mostly survived (like the lowest forms
of ornamentation), yet no one can doubt or deny the gradual and
systematic development of the vegetable and animal kingdoms. If
we find no fragments of pottery in Australia, New Zealand, or the
Polynesian islands, we cannot assume that a grand and powerful
civilisation has perished there, leaving no traces behind. In finding
different kinds of pottery, gradually improving even in the quality of
the material—the clay being first unwashed, then mixed with grains
of quartz and felspar, next carefully washed, then sun-baked, then
fire-baked; first hand and then wheel turned, and at last glazed,
unornamented or ornamented—we cannot assume that the order
was inverted, and that man first ornamented glazed pottery, which
he turned out on the wheel, and then went back to unwashed clay
and hand-made pottery. The ‘degeneration theory’ has exploded as
entirely as the geocentric and anthropocentric theories have
vanished. We know that man, like flowers, trees, rocks and animals,
is the product of the combined forces of nature and the influences of
climate and food, and that his religious, social, and political
conditions are closely reflected in his art. As little as our globe is the
centre of the universe, or man the centre of creation, so little did art
or science spring at once perfectly armed, provided with spear and
shield, from Jupiter’s head like blue-eyed Athene. In a certain sense
art and science are both of divine origin, but only so far as the
originating and creative power is concerned, which, once set in
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like