---
title: "Testovanie — Attributes for Laravel | Roundly"
description: "Zaznamenajte zápisy cez Attributes::fake() a jeho asercie, testujte nad skutočnými riadkami s RefreshDatabase a plňte dáta factory."
url: https://roundly-consulting.com/sk/open-source/navody/attributes-for-laravel/testovanie
language: sk
---

[Všetky balíky](https://roundly-consulting.com/sk/open-source.md)

[Attributes for Laravel](https://roundly-consulting.com/sk/open-source/navody/attributes-for-laravel.md)

# Testovanie

Attributes::fake() nahradí manager zaznamenávajúcim fakom — vo fasáde aj v kontajneri, takže sa zaznamená vložený AttributesManager, handle vlastníka, pripravovaný writer aj každá metóda HasAttributes na modeli. Fake zápisy neblokuje: naďalej idú do testovacej databázy, takže čítanie, validácia aj história fungujú bežne, a každý zápis sa zaznamená, keď uspeje. Definície ďalej používajú skutočný register a nezaznamenávajú sa.

Vráti fake (RoundlyConsulting\\Attributes\\Testing\\AttributesFake) na asercie:

```php
use App\Models\Product;
use RoundlyConsulting\Attributes\Facades\Attributes;

it('records attribute writes', function () {
    $fake = Attributes::fake();
    $product = Product::factory()->create();

    $product->attachAttribute('color', 'red');                    // model method — recorded
    Attributes::for($product)->meta('color', ['hex' => '#f00']);
    Attributes::for($product)->forget('size');
    Attributes::for($product)->sync(['color' => 'red', 'rating' => 5]);
    Attributes::prune(30);

    $fake->assertSet($product, 'color', 'red');                   // with exactly this value
    $fake->assertSet($product, 'color');                          // with any value
    $fake->assertMetaSet($product, 'color', ['hex' => '#f00']);
    $fake->assertForgotten($product, 'size');
    $fake->assertSynced($product, ['rating' => 5, 'color' => 'red']); // exact set, any order
    $fake->assertPruned();

    expect($product->fresh()->getAttachedAttributeValue('rating'))->toBe(5); // writes still hit the database
    expect($fake->recorded())->toHaveCount(5);                                 // list<RecordedWrite>
});

it('writes no attributes on a read-only page', function () {
    $fake = Attributes::fake();

    $this->get('/products')->assertOk();

    $fake->assertNothingSet();
    $fake->assertNothingForgotten();
    $fake->assertNothingSynced();
    $fake->assertNothingMetaSet();
    $fake->assertNothingPruned();
    $fake->assertNothingWritten(); // covers every verb at once
});
```

## Asercie

| Asercia | Negatívna | Zaznamená |
| --- | --- | --- |
| `assertSet($owner, $name, $value?)` | `assertNothingSet()` | set(), setMany() a stage()->save() (jeden záznam na atribút), attachAttribute(s)(). Hodnota sa porovná (===), len ak ju odovzdáte — aj null. |
| `assertForgotten($owner, $name)` | `assertNothingForgotten()` | forget() a forgetExcept() (jeden záznam na odstránený názov), detachAttribute(s)(), destroyAttributes\*(). |
| `assertSynced($owner, ?array $attributes)` | `assertNothingSynced()` | sync(), stage()->sync(), syncAttributes(). S mapou presná množina name => value, v ľubovoľnom poradí. |
| `assertMetaSet($owner, $name, ?array $meta)` | `assertNothingMetaSet()` | meta(), syncAttributeMeta(). |
| `assertPruned()` | `assertNothingPruned()` | prune() a attributes:prune. |
| — | `assertNothingWritten()` | Akýkoľvek zápis. |

$fake->recorded() vráti surový zoznam objektov RecordedWrite (verb, owner, name, value, meta, attributes, forceDelete), keď potrebujete kontrolu, ktorú asercie nepokrývajú.

## Testy nad skutočnými riadkami

Keďže fake zápisy prepúšťa, tabuľky potrebujete tak či tak — balík je obyčajný Eloquent. Publikujte migrácie do aplikácie ako v časti Inštalácia a použite RefreshDatabase:

```php
use App\Models\Product;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
use RoundlyConsulting\Attributes\DataTransferObjects\AttributeDefinitionData;
use RoundlyConsulting\Attributes\Enums\AttributeType;
use RoundlyConsulting\Attributes\Events\AttributeAttached;
use RoundlyConsulting\Attributes\Exceptions\InvalidAttributeValueException;
use RoundlyConsulting\Attributes\Facades\Attributes;

uses(RefreshDatabase::class);

it('stores a typed rating', function () {
    Event::fake([AttributeAttached::class]);

    $product = Product::factory()->create();
    $product->attachAttribute('rating', 5);

    expect($product->getAttachedAttributeValue('rating'))->toBe(5);
    Event::assertDispatched(AttributeAttached::class);
});

it('rejects an out-of-range rating', function () {
    Attributes::define(new AttributeDefinitionData('rating', AttributeType::Integer, rules: ['min:1', 'max:5']));

    Product::factory()->create()->attachAttribute('rating', 9);
})->throws(InvalidAttributeValueException::class);

it('filters products by attribute', function () {
    $white = Product::factory()->create()->attachAttribute('color', 'white');
    Product::factory()->create()->attachAttribute('color', 'black');

    expect(Product::query()->whereAttribute('color', 'white')->pluck('id')->all())
        ->toBe([$white->id]);
});
```

## Testovacie dáta cez factory

Model Attribute má factory so stavmi integerValue(), booleanValue(), ofType(), encrypted() a withMeta(): ofType(AttributeType $type, $value) uloží hodnotu v zadanom type (ofType(AttributeType::Float\_, 5) sa prečíta ako 5.0) — stavajú na ňom integerValue() aj booleanValue() — a encrypted() ju uloží ako šifrový text s príznakom is\_encrypted. K vlastníkovi ju pripojíte cez morph reláciu owner:

```php
use RoundlyConsulting\Attributes\Models\Attribute;

Attribute::factory()
    ->for($product, 'owner')
    ->integerValue(5)
    ->withMeta(['source' => 'seed'])
    ->create(['name' => 'rating']);

Attribute::factory()->for($product, 'owner')->booleanValue()->create(['name' => 'on_sale']);
```

## Tipy

- Definície z konfigurácie sa načítajú raz pri štarte — definície pre konkrétny test registrujte cez Attributes::define(), nie zmenou konfigurácie.
- Register je singleton v kontajneri; v rámci testu ho vynulujete cez Attributes::forget() alebo Attributes::flush().
- Prísny režim aj história sa čítajú pri každom volaní, takže config()->set('attributes.strict', true) či config()->set('attributes.history.enabled', true) v teste platí okamžite.
- Šifrované definície potrebujú kľúč aplikácie — v testovacom prostredí musí byť nastavený APP\_KEY.

Vlastná sada testov balíka sa spúšťa príkazom:

```bash
composer test
```

## Prejavte lásku k open source

Tento balík je zadarmo pod licenciou MIT. Ak vám šetrí čas, jednorazový príspevok alebo členstvo na Patreone nám pomôže ho ďalej udržiavať, testovať a dokumentovať.

[Ďalšie spôsoby podpory vrátane kryptomien](https://roundly-consulting.com/sk/podporte-nas.md)

Odoslaním daru súhlasíte s našimi [podmienkami prijímania darov](https://roundly-consulting.com/sk/podmienky-darov.md).

[Podporte našu open-source prácu (otvorí sa v novej karte)](https://donate.stripe.com/dRmeVe8FX5PF1Qd9pXcEw00) [Pridajte sa k nám na Patreone (otvorí sa v novej karte)](https://www.patreon.com/cw/roundly)

## Chcete to zabudovať do svojho produktu?

Naše balíky integrujeme do zákazkových Laravel a AI riešení. Napíšte nám, na čom pracujete, a ozveme sa do 48 hodín.

[Ponuka do 48 hodín](https://roundly-consulting.com/sk/kontakt.md) [Prezrieť všetky balíky](https://roundly-consulting.com/sk/open-source/navody/attributes-for-laravel.md)
