LiveView did not redirect and Unique Constraint error

I have two flaky tests in my test suite. I think they both have a common root cause.

Failure 1:

test Index saves new post (MyAppWeb.PostLiveTest)
     test/my_app_web/live/post_live_test.exs:33
     ** (RuntimeError) LiveView did not redirect
     code: |> follow_redirect(conn, Routes.post_index_path(conn, :index))
     stacktrace:
       test/my_app_web/live/post_live_test.exs:50: (test)

This is intermittently seen while running my tests.

Failure 2:
This is a different test


** (Ecto.ConstraintError) constraint error when attempting to insert struct:
     
         * posts_name_index (unique_constraint)
     
     If you would like to stop this constraint violation from raising an
     exception and instead add it as an error to your changeset, please
     call `unique_constraint/3` on your changeset with the constraint
     `:name` as an option.
     
     The changeset has not defined any constraint.

In this case, I have added unique_index for :name in my migration and added unique_constraint in the schema. Still it is unable to recognize the unique_constaint. I tried to reset my db but still it throws this error intermittently.

I use factories for my test and this is my post_factory:

def post_factory(attrs \\ %{}) do
    %Post{
      name: attrs[:name] || Faker.Lorem.word()
    }
  end

Can I know if both the unique_constraint error and liveView error are caused by same issue? If not, what is possibly causing the intermittent test failures?

Hi!

Unique constraint error is related to this function: Faker.Lorem.word()
Faker just generates random words, but in the test run, this name could be easily repeated because Faker does not guarantee uniquenes. You should refer to this Faker doc:

Regarding the uniqueness error, you should add the following to your changeset:

https://hexdocs.pm/ecto/Ecto.Changeset.html#unique_constraint/3