Carl Brubaker
Carl Brubaker

Reputation: 1655

Django Testing view template context

I'm trying to test the

return render(request, 'template.html', context)

and seem to be falling short. Is it not worth while testing this? Or if it is worth while testing this, how do I accomplish that?

view.py

def create_employee_profile(request):
    name_form = EmployeeNameForm()
    context = {'name_form':name_form}
    return render(request,
                'template_create_employee_profile.html',
                context
                )

I know the if: else: statements are missing. I didn't think they were relevant to the test.

test.py

# TEST:  context({'name_form':name_form})
def test_CreateEmployeeProfileView_context(self):
    name_form = EmployeeNameForm()
    response = self.client.get(reverse(
                            'create_employee_profile'))
    self.assertEquals(response.context['name_form'], name_form)

This got me the closest to success. Here's my error:

AssertionError: <Empl[27 chars]alid=False,
                fields=(employee_choices;first_nam[20 chars]ame)> != 
                <Empl[27 chars]alid=Unknown,
                fields=(employee_choices;first_n[22 chars]ame)>

What about the detail view?

# TEST:  context({'name':name})
def test_CustomerEmployeeProfileView_context(self):
    name = CustomerEmployeeName.objects.get(pk=1)
    response = self.client.get(
        reverse('service:customer_employee_profile_detail', kwargs={'pk': 1}))

    self.assertIsInstance(response.context['name'], name)

Got this error:

TypeError: isinstance() arg 2 must be a type or tuple of types

Upvotes: 12

Views: 10886

Answers (1)

solarissmoke
solarissmoke

Reputation: 31404

You are comparing two different instances of the EmployeeNameForm, which is why the assertion fails.

If you just want to test that the context variable is indeed a EmployeeNameForm then you can test it with assertIsInstance:

def test_CreateEmployeeProfileView_context(self):
    response = self.client.get(reverse('create_employee_profile'))
    self.assertIsInstance(response.context['name_form'], EmployeeNameForm)

Upvotes: 18

Related Questions