Search code examples
djangoseleniumdjango-formstdd

Cant Get POST Unit Test To Update Data Working


I am trying to make a unit test in Selenium to check that my POST works on my user profile page (users are able to update their profile information). My problem is that I cant get it to work (I cant get the unit test to update the users email) - I've tried many things but cant get it right.

This test returns: AssertionError: 'user@example.com' != 'update@example.com'

views.py

@login_required
def update_profile(request):

    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
        if u_form.is_valid() and p_form.is_valid():
           u_form.save()
           p_form.save()
           messages.success(request, f'Your account has been updated')
           return redirect('update_profile')
    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)

    context = {
        'u_form' : u_form,
        'p_form' : p_form
    }

    return render(request, 'users/update_profile.html', context)

form.py

class UserUpdateForm(forms.ModelForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email']

test.py

def test_update_works(self):
        user = User.objects.create(username='testuser', email='user@example.com')
        self.client.force_login(user)
        self.client.post('/profile/update_profile',{'email': 'updated@example.com'},)
        self.assertEqual(user.email, 'updated@example.com')

Thank you.


Solution

  • You have the old user information in memory, before the update was done. You need to "refresh" your user information from the database and then check against the new email.

    def test_update_works(self):
        user = User.objects.create(username='testuser', email='user@example.com')
        self.client.force_login(user)
        self.client.post('/profile/update_profile',{'email': 'updated@example.com'},)
        user.refresh_from_db() # here you get the latest info
        self.assertEqual(user.email, 'updated@example.com')