Where with ranges of values

Ecto for Beginners : part 11 of 22 published on Sep 06, 2015
# /test/models/posts/where_votes_test.exs
defmodule Readdit.Posts.WhereTitleTest do
  use ExUnit.Case
  use Readdit.ConnCase
  import Ecto.Query

  setup do
    %Readdit.Post{title: "Han Shot First", votes: 10 } |> Readdit.Repo.insert!
    %Readdit.Post{title: "Tony Stark is Iron Man", votes: 150 } |> Readdit.Repo.insert!
    %Readdit.Post{title: "R2D2 is the best!", votes: 26} |> Readdit.Repo.insert!
    %Readdit.Post{title: "Rosetta Stone for Wookies", votes: 3} |> Readdit.Repo.insert!

    :ok
  end

  test "where votes == 3 |> all" do
    posts = Readdit.Post
    |> where([p], p.votes == 3)
    |> Readdit.Repo.all

    assert Enum.count(posts) == 1

    [post|_] = posts
    assert post.title == "Rosetta Stone for Wookies"
  end

  test "where votes < 20 |> all" do
    posts = Readdit.Post
    |> where([p], p.votes < 20)
    |> Readdit.Repo.all

    assert Enum.count(posts) == 2
  end

  test "where votes > 30 |> all" do
    posts = Readdit.Post
    |> where([p], p.votes > 30)
    |> Readdit.Repo.all

    assert Enum.count(posts) == 1

    [post|_] = posts
    assert post.title == "Tony Stark is Iron Man"
  end

  test "where votes > 5 and votes < 50 |> all" do
    posts = Readdit.Post
    |> where([p], 5 < p.votes)
    |> where([p], p.votes < 50)
    |> Readdit.Repo.all

    assert Enum.count(posts) == 2
  end

end
Next: Query with date ranges