/** * @test */ function it_validates_attributes() { $data = new Helpers\TestDataObject(); // validate empty data against single required rule $this->assertFalse($data->validate(), 'empty should not pass validation'); $messages = $data->messages(); $this->assertInstanceOf(MessageBag::class, $messages, 'validation messages not of correct type'); $this->assertCount(1, $messages, 'validation messages should have 1 message'); $this->assertRegExp('#name .*is required#i', $messages->first(), 'validation message not as expected for empty data'); // validate partially incorrect data $data->name = 'Valid name'; $data->list = 'not an array'; $this->assertFalse($data->validate(), 'incorrect data should not pass validation'); $messages = $data->messages(); $this->assertCount(1, $messages, 'validation messages should have 1 message'); $this->assertRegexp('#list .*must be an array#i', $messages->first(), 'validation message not as expected for incorrect data'); // validate correct data should be okay $data->name = 'Valid name'; $data->list = ['one' => 'present']; $this->assertTrue($data->validate(), 'Correct data should pass validation'); }
/** * @test */ function it_validates_nested_data_objects_for_required_nested_invalid_data() { $data = new TestNestedDataObject(); $this->assertFalse($data->validate(), "validation should fail for empty"); $nestedData = new TestDataObject(['irrelevant' => 'nothing']); $this->assertFalse($nestedData->validate(), "validation should fail for empty nested (on its own)"); $data->nested = $nestedData; $this->assertFalse($data->validate(), "validation should fail for empty nested (when nested)"); // the messages should indicate that the name field is missing from the nested object $messages = $data->messages(); $this->assertCount(2, $messages, "should be two messages in the bag (1 for nested, 1 for nested content"); $this->assertRegExp('#name .*required#i', $messages->get('nested.name')[0], 'Incorrect or missing message for nested name'); $this->assertEquals('validation.dataobject', $messages->get('nested')[0], 'Incorrect or missing message for nested main'); // Note that the validation.dataobject message is the custom message for which there is // no translation in this test! }