Home > Mobile >  Pytest: Test user-editing view, object is not updating
Pytest: Test user-editing view, object is not updating

Time:06-22

I want to test my account_edit view, if the user's/customer's info is being updated properply. I'm new to pytest.

View:

@login_required
def account_edit(request):
    if request.method == "POST":
        user_form = UserEditForm(instance=request.user, data=request.POST)
        if user_form.is_valid():
            user_form.save()
    else:
        user_form = UserEditForm(instance=request.user)
    return render(request, "account/user/edit_account.html", {"user_form": user_form})

Factory:

class CustomerFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Customer
        django_get_or_create = ("email",)

    email = "[email protected]"
    name = "user1"
    mobile = "123456789"
    password = "user1"
    is_active = True

the test_account_views.py:

@pytest.mark.django_db
def test_account_edit_post(client, customer_factory):
    user = customer_factory.create()
    client.force_login(user)
    response = client.post(
        "/account/edit/",
        data={
            "name": "newname",
            "email": "[email protected]",
        },
    )
    print(user.name)
    assert response.status_code == 200

When Im printing out the email print(user.name) Im expecting it to be updated with newname. However receiving the old one (user1) AND the response status is also OK: 200. So it seems the problem is just that the user isn't updating. The problem is with testing code, not the django app itself(checked it). Thanks in advance for any help.

CodePudding user response:

You are printing user.name of user which you have already got from database. After it's changed in POST request you need to refresh it using refresh_from_db() method like that user.refresh_from_db() then print user.name

  • Related