django app pytest Key error while testing

Viewed 85

I have a problem regarding testing one of views in my django app. I use pytest.

Here is the view i'm gonna test:

class IngredientDetailsView(View):
    def get(self, request, id):
        ingredient = Ingredient.objects.get(id=id)
        return render(request, 'diet_app/ingredient_details.html', {'ingredient': ingredient})

and it's model:

class Ingredient(models.Model):
    name = models.CharField(max_length=50, unique=True)
    nutrient = models.IntegerField(choices=NUTRIENTS)
    glycemic_index = models.IntegerField(choices=GLYCEMIC_INDEX)

Here is my fixture and test:

@pytest.fixture
def example_ingredient():
    return Ingredient.objects.create(
        name='apple',
        nutrient=2,
        glycemic_index=2
    )


@pytest.mark.django_db
def test_ingredient_view(client, example_ingredient):
    response = client.get(f'/ingredient_details/{example_ingredient.id}/')
    assert response.status_code == 200
    assert response.context['name'] == 'apple'
    assert response.context['nutrient'] == 2
    assert response.context['glycemic_index'] == 2

I still face KeyErrors:

FAILED diet_app/tests.py::test_ingredient_view - KeyError: 'name'

and don't know why.

I'm a fresher using pytest and still learning. I suppose the problem are asserts fields in my test because when i removed field 'name' key error changed to 'nutrient'

0 Answers
Related