Skip to content Skip to sidebar Skip to footer

Reusing Pytest Fixture In The Same Test

Below is an example of test code that uses a user fixture to setup the test. @pytest.fixture def user(): # Setup db connection yield User('test@example.com') # Close db

Solution 1:

The pytest documentation had a "factories as fixtures"-section that solved my problem.

This example in particular (copy/pasted from the link):

@pytest.fixture
defmake_customer_record():

    created_records = []

    def_make_customer_record(name):
        record = models.Customer(name=name, orders=[])
        created_records.append(record)
        return record

    yield _make_customer_record

    for record increated_records:
        record.destroy()


deftest_customer_records(make_customer_record):
    customer_1 = make_customer_record("Lisa")
    customer_2 = make_customer_record("Mike")
    customer_3 = make_customer_record("Meredith")

Post a Comment for "Reusing Pytest Fixture In The Same Test"