phpspec
SpecBDD Framework for PHP
phpspec
How to test with phpspec that parent-child biedirectional relations are created properly?
class ParentSpec extends ObjectBehavior
{
function it_adds_a_reference_to_self_while_(Child $child)
{
$this->addChild($child);
$child->setParent($this)->shouldBeCalled();
}
}
Line 7 throws an error, which is obious because $this
is a ParentSpec
object not Parent
. But I have no other ideas how to test that setParent
method has been called.
Source: (StackOverflow)
When writing test cases inthe xUnit style that PHPUnit follows it seems that everyone follows the camel case convention for function names:
public function testObjectHasFluentInterface()
{
// ...
}
I have been naming my methods with a more "eloquent" PHPSpec style:
public function test_it_has_a_fluent_interface()
{
// ...
}
Will this style create problems for me in the future? Personally I find it vastly more readable and easy to come back to.
Source: (StackOverflow)
Does anyone know a method to generate coverage reports from PHPSpec tests?
I thought about xdebug, but as far as I know it cant generate reports for jenkins.
Source: (StackOverflow)
I am currently doing research into which test framework I should be using for php. The two choices I have are PHPUnit and PHPSpec. I know that PHPUnit is TDD(Test driven development) and PHPSpec is BDD(Behavior driven development). However due to the lack of any real PHPSpec tutorial and limited documentation on the PHPSpec site I am unable to come to a full conclusion. My question to everyone is what are some addition similarities and differences between the two frameworks? Yes BDD and TDD are big ones but are there others? And they seem similar but no one talks about their similarities in great detail. Thank you.
Source: (StackOverflow)
I have been wrestling with this question for far too long now. I know I need to just jump into one or the other since they are both obviously viable/useful tools, but have been stuck on the fence, researching both, for weeks.
PHPUnit vs. PHPSpec - Which one may lead to better long-term maintainability and programming practices?
I have talked to several seasoned PHPUnit -> PHPspec converts/users who now swear by PHPspec, claiming that it promotes better design thanks to its BDD approach. However, since it is a much newer tool there is a lack of community/tutorials in comparison with PHPUnit.
Currently, my PHP development is focused around Laravel 4 development.
Where PHPUnit is basically baked into the Laravel framework, it seems like that may be the easier choice up front, but I really like the BDD aspect of PHPSpec. However, it seems that PHPSpec doesn't want to play nicely with Laravel's facade setup (which I'm also finding may be a good practice to steer clear of when possible).
My real conundrum is which of these will be more likely to be successfully integrated into an existing Laravel 4 project with zero existing test coverage.
I had an early/brief stab at integrating both PHPUnit and PHPSpec into an existing project, but really just wasn't sure where to begin with writing the initial tests and ended up scrapping them for the time being.
I am really trying to sort out which one may be more worth investing some time into in the long run.
Any resources/insight from anyone who has experienced both would be greatly appreciated.
Source: (StackOverflow)
I've just started learning phpspec with a view to replacing PHPUnit. Unfortunately, I've got rather hooked on using the PHPStorm editor's code completion feature, which makes even PHPUnit's verbose mock interface very quick to type.
No such luck with phpspec. Given a class like this:
<?php
namespace spec\MyVendor\MyClass;
use PhpSpec\ObjectBehavior;
class MyClassSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('MyVendor\MyClass');
}
function it_should_do_something()
{
$this->???
}
}
Firstly, shouldHaveType
is showing the 'method not found' highlight, and secondly, if I try to autocomplete at the ???
point, my options are limited to the few methods in ObjectBehaviour
. I would want to see things like shouldHaveType
, shouldImplement
, and many more.
I've found this phpspec-stubs repository on Github, but it seems to only have one method defined, and requires extending a wrapper class.
There's also a PHPStorm plugin but it's not clear to me if this should provide auto-complete, and the current version gives me a NullPointerException in PHPStorm immediately on entering any PHP file.
So, are all you phpspec users typing a lot, or is there another solution?
Source: (StackOverflow)
I am using phpspec to test our application. Now we need to develop some commands and therefore I want to spec these as well.
I am a bit stuck here, because the docs (http://symfony.com/doc/master/cookbook/console/console_command.html#testing-commands) only tell me how to test the commands using phpunit.
Even if I would use a similar approach (creating the kernel somehow, and instantiating the command in question) in the specs I think that this would not follow the idea of describing behaviour. I would only spec, whether the output is correct or not, but not if the command is calling the right methods and so on.
Has anyone used phpspec to successfully describe Symfony2 commands? What would be a feasible approach of doing this?
Thanks
Source: (StackOverflow)
Searched stackoverflow for this and found no answer
Coming from Ruby On Rails and Rspec, I need a tool like rspec (easier transition). Installed it through PEAR and tried to run it but it's not working (yet)
Just wanna ask around if anyone's using it have the same problem, since it's not running at all
tried running it with an example from the manual - http://dev.phpspec.org/manual/en/before.writing.code.specify.its.required.behaviour.html
phpspec NewFileSystemLoggerSpec
returns nothing
even running
phpspec some_dummy_value
returns nothing
Source: (StackOverflow)
I am setting up a new Laravel project and integrating PHPSpec. I am having trouble finding a good working example of the phpspec.yml file that would work neatly with Laravel. In a similar way to RSpec in Rails.
My desired folder structure would be as follows
spec/
models/
controllers/
app/
models/
controllers/
My phpspec.yml currently looks like this:
suites:
controller_suite:
namespace: Controller
spec_path: 'spec/controllers'
src_path: 'app/controllers'
model_suite:
namespace: Model
spec_path: 'spec/models'
src_path: 'app/models'
I copied my Model related tests in the spec/models folder, but when I 'phpspec run' it does not run any of them.
I also realise that the namespace is not 'Model' and 'Controller' in Laravel, perhaps more like Eloquent and BaseController..
I am also using this extension: https://github.com/BenConstable/phpspec-laravel
I'm not sure how to set this up and cannot find any working examples.
Thanks in advance!
EDIT:
Advice founbd on another forum from Jeffrey Way:
You can test your controllers with Behat. PHPSpec isn't a substitute
for it (or Codeception).
UPDATE:
I've since decided to use Codeception instead as it seems to integrate neatly into Laravel and widely used.
Source: (StackOverflow)
i try to use the let function with scalar values.
My problem is that the price is an Double, i expected an int 5.
function let(Buyable $buyable, $price, $discount)
{
$buyable->getPrice()->willReturn($price);
$this->beConstructedWith($buyable, $discount);
}
function it_returns_the_same_price_if_discount_is_zero($price = 5, $discount = 0) {
$this->getDiscountPrice()->shouldReturn(5);
}
the error:
✘ it returns the same price if discount is zero
expected [integer:5], but got [obj:Double\stdClass\P14]
is there a way to inject the 5 using the let function?
Source: (StackOverflow)
I have a phpspec class like below and I only want to run a single spec from it. I would like to run the "it_should_do_something_easy" only. Is this possible?
This is how I run this spec file:
$> phpspec run spec/Project/WorkerSpec.php
But now I only want to run a single spec like "it_should_do_something_easy".
<?php
namespace spec\Project;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class WorkerSpec
{
public function it_should_do_something_easy()
{
$this->doSomethingEasy()->shouldReturn('Done!');
}
public function it_should_do_something_hard()
{
$this->doSomethingHard()->shouldReturn('Too hard!');
}
}
Source: (StackOverflow)
I am new to testing and I'm not sure I go about this the right way:
I want to not to do a unit test on a specific class but on whatever class get resolved out of my ioc container. In the ioc container I bind my interfaces to concrete classes, like so:
Example (I'm using Laravel 5):
// in a service provider
public function register(){
$this->app->bind('FooInterface', function() {
return new SomeConcreteFoo;
});
}
Then I want to write unit test against FooInterface
and not SomeConcreteFoo
which could be swapped out with some other class at a later point.
The reason I want to do this is that it seems to me that the relevant testing should target whatever my ioc container returns, since that is what I'll be using in the application. It also seems to me that the testing should be done on the interface level, since that is where I define the expectations the rest of the app will have to my class.
I'm having a hard time finding any information on how to do this, which suggests to me that I might think about this the wrong way. For instance maybe what I'm trying to accomplish is more like an integration test rather than a unit test.
So the first question is: am I thinking about testing this the right way? in case I'm not - do you have any suggestions regarding best practice for an alternative test path.
The second question: In case my thinking is sound - how do I setup phpspec to make use of the Laravel IOC container, so that I can test against whatever the IOC returns..
Source: (StackOverflow)
I am having some trouble running tests for PUT
, POST
and DELETE
using the unit testing framework phpspec2.
This is the code that I have in my unit test:
$this->beConstructedWith(new \Tonic\Application(), new \Tonic\Request(array(
'uri' => '/',
'method' => 'PUT',
'Content-Type' => 'application/json',
'data' => '{"name":"testing", "email":"testing@@test.com", "password":"Passw0rd"}'
)), array());
$expectedResult = new \stdClass();
$expectedResult->message = "An error was encountered.";
$expectedResult->error[] = "The email must be valid.";
$response = $this->exec();
$response->shouldReturnAnInstanceOf("Tonic\Response");
$response->contentType->shouldBe("application/json");
$response->body->shouldBe(json_encode($expectedResult));
From looking around the Tonic code and the examples in the git repository I think I have it set up correctly.
The following is the result of running bin/phpspec -v run
for this unit test:
When I run an actual request against the Tonic service it works fine. I know I must be doing something wrong in the setup of the unit test but I don't know what.
Edit: PUT Method
/**
* Add a new user to the table.
*
* @method PUT
* @accepts application/json
* @provides application/json
* @json
* @return \Tonic\Response
*/
public function add()
{
// Validate the data before we go any futher.
$error = $this->validate();
// If the data is invalid then we want to let the requester know.
if (true === $error) {
$this->output->message = "An error was encountered.";
$this->responseCode = \Tonic\Response::NOTFOUND;
} else { // Else we want to PUT the data into our table.
$query = $this->db->prepare("INSERT INTO `user` (`name`, `email`, `password`, `dateOfBirth`) VALUES (:name, :email, :password, :dateOfBirth)");
$query->bindValue(":name", $this->request->data->name);
$query->bindValue(":email", $this->request->data->email);
$query->bindValue(":password", hash('sha256', $this->request->data->password));
$query->bindValue(":dateOfBirth", $this->request->data->dateOfBirth);
$query->execute();
// Check that the new user was successfully inserted into the database. If not let the requester know what happened.
if (0 === $query->rowCount()) {
if ("00000" === $query->errorCode()) {
$this->output->message = "No rows affected by query.";
} else {
$this->output->message = "There was an error running the query.";
$this->output->error[] = $query->errorInfo();
}
$this->responseCode = \Tonic\Response::CONFLICT;
} else { // Inserted successfully.
$this->output->message = "User successfully created.";
$this->responseCode = \Tonic\Response::CREATED;
$this->headers["Location"] = "/" . $this->request->data->email;
}
}
return new \Tonic\Response($this->responseCode, $this->output, $this->headers);
}
Source: (StackOverflow)
I am trying to test a data transfer object class which constructs with Symfony\Component\HttpFoundation\File\UploadedFile.php
class in Laravel. I've had no luck testing this implementation in PHPSpec
. Here is what I have so far:
Test
public function let($event_id)
{
$prophet = new Prophet;
$prophecy = $prophet->prophesize();
$prophecy->willBeConstructedWith(array('path', 'name'));
$prophecy->willExtend('Symfony\Component\HttpFoundation\File\UploadedFile');
$attendee_list = $prophecy->reveal();
$this->beConstructedWith($event_id, $attendee_list);
}
public function it_is_initializable()
{
$this->shouldHaveType('Captix\Attendees\ImportAttendeesCommand');
}
Class
class ImportAttendeesCommand
{
/**
* Event primary key
* @var $event_id
*/
protected $event_id;
/**
* CSV file
* @var $attendee_list
*/
protected $attendee_list;
/**
* Constructor for ImportAttendeesCommand
*/
public function __construct($event_id, UploadedFile $attendee_list)
{
$this->event_id = $event_id;
$this->attendee_list = $attendee_list;
}
}
Result
2 -_-__,------,
0 -_-__| /\_/\
0 -_-_^|__( o .o)
1 -_-_ "" ""
Captix/Attendees/ImportAttendeesCommand
38 ! it is initializable
exception [exc:Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException("The file "path" does not exist")] has been thrown.
0 vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/File/File.php:41
throw new Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException("The file "path" does not ...")
1 vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/File/UploadedFile.php:100
Symfony\Component\HttpFoundation\File\File->__construct("path", true)
2 vendor/phpspec/prophecy/src/Prophecy/Doubler/Generator/ClassCreator.php(49) : eval()'d code:6
Symfony\Component\HttpFoundation\File\UploadedFile->__construct("path", "name", null, null, null, null)
3 [internal]
Double\Symfony\Component\HttpFoundation\File\UploadedFile\P4->__construct("path", "name")
4 vendor/phpspec/prophecy/src/Prophecy/Doubler/Doubler.php:109
ReflectionClass->newInstanceArgs([array:2])
5 vendor/phpspec/prophecy/src/Prophecy/Doubler/LazyDouble.php:119
Prophecy\Doubler\Doubler->double([obj:ReflectionClass], [array:0], [array:2])
6 vendor/phpspec/prophecy/src/Prophecy/Prophecy/ObjectProphecy.php:114
Prophecy\Doubler\LazyDouble->getInstance()
7 app/Spec/Captix/Attendees/ImportAttendeesCommandSpec.php:33
Prophecy\Prophecy\ObjectProphecy->reveal()
8 [internal]
Spec\Captix\Attendees\ImportAttendeesCommandSpec->let([obj:PhpSpec\Wrapper\Collaborator])
3 examples (2 passed, 1 broken)
119ms
I've tried several ways to test this, using Mockery, Prohpecy, stdClass, nothing seems to be working. Any help on this would be much appreciated. I am welcome to any implementation of this test. Thanks to all in advance.
Source: (StackOverflow)
I am stumbling a bit with finding a way to test that my exception handler is being called upon thrown Exception.
This is the idea that I initially working with for the testing:
class ClientSpec extends ObjectBehavior
{
function it_should_catch_exceptions(Config $config)
{
$e = new Exception('test exception');
$this->catchException($e)->shouldBeCalled();
throw $e;
}
}
The Client
has a method catchException
which will be set as exception handler through set_exception_handler
: http://php.net/set_exception_handler.
Running this test gives me this feedback: no beCalled([array:0]) matcher found for null
, so I've also tried to do create a spec for Exception
and do the following:
class ExceptionSpec extends ObjectBehavior
{
function it_should_trigger_opbeat_client_when_thrown(Client $client)
{
$client->catchException($this)->shouldBeCalled();
throw $this->getWrappedObject();
}
}
But running this test returns another error: exception [exc:Exception("")] has been thrown
How can I test that my exception handler is called?
Source: (StackOverflow)