Testing an Ecto query is correct

287 views
Skip to first unread message

garydav...@gmail.com

unread,
Jul 23, 2016, 12:36:04 PM7/23/16
to phoenix-talk

Hi - I am an elixir newb and phoenix newb as well. Coming from a ruby / rails background.  I am cracking on with learning how to do some of the basics and now moved on to test driven development using espec - although this question really applies to exunit as well.  

I have a function which has an ecto query as its input and is expected to extend this ecto query with a simple “where id=x” and call Repo.one(query), the result is then returned to the caller.


What is the recommended way of proving this - I am thinking avoiding hitting the database just to prove a query.

So far, I have mocked the repo and expected a call to “one” with a query, but the code I have written to test the query is awful, so I am thinking there must be a better way..


This is my mock code - as you can see, it is awful - has deep knowledge of the internals of Ecto - and I am unsure how accurate that knowledge is - this was established from an iex session.


expect(shared.mock_repo) |> to accept :one, fn(query) ->
tagged_ecto_query = hd(query.wheres).expr |> Tuple.to_list |> List.last |> List.last
if tagged_ecto_query.type |> elem(1) == :id && tagged_ecto_query.value == 12 do
shared.correct_record
else
nil
end
end

Thibaut Barrère

unread,
Jul 23, 2016, 12:44:43 PM7/23/16
to phoeni...@googlegroups.com
I personally prefer to hit the database for such tests (and avoid mocking completely).

You may find ex_machina useful to have a factory_girl like experience in Elixir.

-- Thibaut

garydav...@gmail.com

unread,
Jul 23, 2016, 1:01:06 PM7/23/16
to phoenix-talk
Thanks Thibaut - I'll look into that.
Reply all
Reply to author
Forward
0 new messages