mercredi 28 septembre 2016

How to implement an "assert_difference" for ExUnit

I'd like to test how a function changes something in the database. I'm struggling with an ExUnit equivalent of the following ActiveSupport::TestCase test case:

test "creates a database record" do
  post = Post.create title: "See the difference"
  assert_difference "Post.published.count" do
    post.publish!
  end
end

The RSpec version is more elegant and, because of its use of lambdas, something I thought was portable to Elixir/ExUnit.

it "create a database record" do
  post = Post.create title: "See the difference"
  expect { post.publish! }.to change { Post.count }.by 1
end

Is there a more elegant (read: functional) way to do it than this:

test "creates a database record", %{conn: conn} do
  records_before = count_records
  post(conn, "/articles")
  records_after  = count_records

  assert records_before == (records_after - 1)
end

defp count_records do
  MyApp.Repo.one((from a in MyApp.Article, select: count("*"))
end

Aucun commentaire:

Enregistrer un commentaire