Test cases for a library

I am writing test cases for a library which makes dynamic queries for where, joins, select easy.

I have created models which don’t persist in the database and test these functions.

Each of these functions return the query,

I am testing these functions to see if they build up a correct query not the ecto

This is the code:

 test "returns the query where field like" do
   opts = %{
    "$where" => %{"first_name" => %{"$like" => "%Ham %"}}
   }
  expected = from w in TestModel.Where, where: like(w.first_name, ^"%Ham %")
  assert build(TestModel.Where, opts) == expected
end

expected is the query which it returned in the console.

This is what i get in return when I try to run the tests and it failed.

left side of assert is pointed to the function file and right side to the test file

Any suggestions or idea about better approach.

Thanks

You can compare the final sql as a string, or an “inspect” representation of the query. You can also nilify the values for :file key on both sides, or add an additional macro like assert_query to do it for you automatically.

can you elaborate it farther please or link to any documentation

Sorry, should have been more clear.


You can compare the final sql as a string

https://hexdocs.pm/ecto/Ecto.Adapters.SQL.html#to_sql/3

{built_sql, _assigns} = Repo.to_sql(:all, build(TestModel.Where, opts))
{expected_sql, _assigns} = Repo.to_sql(:all, expected)
assert built_sql == expected_sql

or an “inspect” representation of the query

https://hexdocs.pm/elixir/Kernel.html#inspect/2

assert inspect(build(TestModel.Where, opts)) == inspect(expected)

You can also nilify the values for :file key on both sides

built = %{build(TestModel.Where, opts) | file: nil}
expected = %{expected | file: nil}
assert built == expected
1 Like

Thanks