How to unit test Vapor DB Objects

Viewed 54

I have the following simple object relationship:

public final class Planet: Model {
    
    @ID(key: .id)
    public var id: UUID?
    
    @Parent(key: .starId)
    public var star: Star

It all works OK when the application runs with the real db where the parent is queried from the database before assigning to the child. I have a number of unit tests in the logic level where I need an object to test some conditions and there is no database i.e. so naively I do

let star = Star()
var planet = Planet()
planet.star = star

This fails on the last line with exception "use $ prefix to access". The error is bogus, the real reason is that Vapor/Fluent objects are tied to the database. Is there a simple way to make this work without instantiating a database?

1 Answers

The error is not bogus, the error is correct. It's to do with the way property wrappers work and Fluent needing to protect accesses to relations in case they haven't been eager loaded.

If you want to manually set a relation you can do

planet.$star.value = star

You can find more information (and the above code example) in the docs

Related