it("lazy loads a hasOne relation", function () { Stub::on(GalleryDetail::class)->method('::all', function ($options = [], $fetchOptions = []) { $details = GalleryDetail::create([['id' => 1, 'description' => 'Foo Gallery Description', 'gallery_id' => 1]], ['type' => 'set', 'exists' => true, 'collector' => $fetchOptions['collector']]); return $details; }); $gallery = Gallery::create(['id' => 1, 'name' => 'Foo Gallery'], ['exists' => true]); expect(GalleryDetail::class)->toReceive('::all')->with(['conditions' => ['gallery_id' => 1]], ['collector' => $gallery->collector()]); expect($gallery->detail->gallery_id)->toBe($gallery->id); expect($gallery->detail->collector())->toBe($gallery->collector()); }); }); describe("->save()", function () { it("bails out if no relation data hasn't been setted", function () { $hasOne = Gallery::relation('detail'); $gallery = Gallery::create(['id' => 1, 'name' => 'Foo Gallery'], ['exists' => true]); expect($hasOne->save($gallery))->toBe(true); }); it("saves a hasOne relationship", function () { $hasOne = Gallery::relation('detail'); $gallery = Gallery::create(['id' => 1, 'name' => 'Foo Gallery'], ['exists' => true]); $gallery->detail = ['description' => 'Foo Gallery Description']; Stub::on($gallery->detail)->method('save', function () use($gallery) { $gallery->detail->id = 1; return true; }); expect($gallery->detail)->toReceive('save'); expect($hasOne->save($gallery))->toBe(true); expect($gallery->detail->gallery_id)->toBe($gallery->id); }); }); });
Stub::on($gallery->images[0])->method('save', function () use($gallery) { $gallery->images[0]->id = 1; return true; }); expect($gallery->images[0])->toReceive('save'); expect($hasMany->save($gallery))->toBe(true); expect($gallery->images[0]->gallery_id)->toBe($gallery->id); }); it("assures removed association to be unsetted", function () { $toUnset = Image::create(['id' => 2, 'gallery_id' => 1, 'title' => 'Srinivasa Ramanujan'], ['exists' => true]); $toKeep = Image::create(['id' => 3, 'gallery_id' => 1, 'title' => 'Las Vegas'], ['exists' => true]); Stub::on(Image::class)->method('::all', function ($options = [], $fetchOptions = []) use($toUnset, $toKeep) { $images = Image::create([$toUnset, $toKeep], ['type' => 'set']); return $images; }); $hasMany = Gallery::relation('images'); $gallery = Gallery::create(['id' => 1, 'name' => 'Foo Gallery'], ['exists' => true]); $gallery->images = [['title' => 'Amiga 1200'], $toKeep]; Stub::on($gallery->images[0])->method('save', function () use($gallery) { $gallery->images[0]->id = 1; return true; }); Stub::on($toUnset)->method('save', function () use($toUnset) { return true; }); expect($gallery->images[0])->toReceive('save'); expect($toKeep)->toReceive('save'); expect($toUnset)->toReceive('save'); expect($hasMany->save($gallery))->toBe(true); expect($toUnset->exists())->toBe(true); expect($toUnset->gallery_id)->toBe(null);