Date post: | 28-Jan-2018 |
Category: |
Software |
Upload: | david-hulbert |
View: | 653 times |
Download: | 0 times |
What is TDD?
1) Write a failing test (red)
2) Write the minimum amount of code to pass the test (green)
3) Refactor (restructure code, without changing its behaviour)
Why TDD?
● Don't write code that isn't needed● Write fewer bugs● Write more maintainable code● Be more productive
$ mkdir phpspec-demo$ cd phpspec-demo$ composer require --dev phpspec/phpspec$ alias spec=./vendor/bin/phpspec
Setup
$ vim composer.json $ cat composer.json { "require-dev": { "phpspec/phpspec": "^2.3" }, "autoload": { "psr-0": {"": "src"} }}$ mkdir src$ composer update --lock
Setup
$ spec list...Available commands: describe Creates a specification for a class help Displays help for a command list Lists commands run Runs specifications
Features
$ spec desc Blog
Specification for Blog created in /home/dave/phpspec-demo/spec/BlogSpec.php.
Write a spec
Refactor
● Rename method/variable● Extract/inline method/variable● Replace loop with collection● Replace conditional with polymorphism● Replace inheritance with delegation
PhpSpec MatchersshouldReturn('hello')shouldThrow(\Exception::class) ->duringSetCount(-1)shouldHaveType(User::class)shouldHaveCount(3)shouldBeString()shouldBeInt()shouldBePublished() → isPublished()shouldHaveContent() → hasContent()
Pro tips
● Use interfaces if you want to talk to collaborators
● Refactor the SUS and the specs
● Don't be afraid to delete specs when they're not helpful
● Painful to spec means you have a bad design● Use PhpSpec to design how objects talk to each other (internal
behaviour)
● Use PHPUnit to write tests (eg integration)
● Use Behat to specify external behaviour