I’m in a pickle. I’m working through my first app and have decided to be disciplined and create tests as I go for each new feature.
As far as this goes, I’m stuck on what I feel should be a basic fundamental thing… I haven’t been able to grasp it…
I have a field ‘created_by’ in my model which is automatically populated by the current logged in user. Works fine…
But how on earth do I put this instance into my tests? I’m building from Mosh’s testing tutorials in the course but it only covers authenticated user or not… not actually passing an instance into the endpoint.
The error I get is:
ValueError: Cannot assign “<User: >”: “Catalogue.created_by” must be a “User” instance.
@pytest.fixture
def create_catalogue(api_client):
def do_create_catalogue(catalogue):
return api_client.post('/companies/1/catalogues/', catalogue)
return do_create_catalogue
@pytest.mark.django_db
class TestCreateCatalogue:
def test_if_data_is_valid_returns_201(self, authenticate, create_catalogue):
authenticate(is_staff=True)
user = 'this is where i guess i need to get the user instance'
response = create_catalogue({'title': 'a', 'created_by':user})
assert response.status_code == status.HTTP_201_CREATED
assert response.data['id'] > 0
Resulting error:
ValueError: Cannot assign “<User: >”: “Catalogue.created_by” must be a “User” instance.
You would just have to query the default user table for the user.
If you do not know the specific user instance id to query, you can just call User.objects.all().first() which will get the first user instance it finds in the table.