Open atomkirk opened 7 years ago
Thanks for the comment.
then I can use setup/on_exit to insert/eject based on if that tag is present!
I couldn't understand this part well (for how/when tag should be used?)
like this:
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(ZB.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(ZB.Repo, {:shared, self()})
end
if tags[:cassette] do
ref = insert_cassette(tags[:cassette])
on_exit fn -> eject_cassette(ref) end
end
{:ok, conn: build_conn()}
end
end
Then the cassette "blah" would be inserted before the test began and ejected after it exited:
@tag cassette: "blah"
test "much more simple" do
…my test…
end
I got this sort of working with the following code:
defmodule MyApp.VCRCase do
@moduledoc """
This module defines a tag to remove the boilerplate of using ExVCR.
## Example:
defmodule Foo.Bar do
@tag :vcr
test "my wonderful test" do
# the recording will be stored in "Elixir.Foo.Bar/my_wonderful_test.json"
end
end
All the options you'd usually pass to `use_cassette` can be passed to @tag:
defmodule Foo.Bar do
@tag vcr: [match_requests_on: [:query]]
test "my wonderful test" do
end
end
"""
use ExUnit.CaseTemplate
using do
quote do
setup context do
setup_vcr(context)
:ok
end
defp setup_vcr(%{vcr: opts} = context) when is_list(opts) do
describe_name = context[:describe] || ""
test_name =
context.test
|> to_string()
|> String.replace("test #{describe_name} ", "")
fixture =
[to_string(__MODULE__), describe_name, test_name]
|> Enum.map(&normalize_fixture(&1))
|> Enum.join("/")
opts = opts ++ [fixture: fixture, adapter: ExVCR.Adapter.IBrowse]
recorder = ExVCR.Recorder.start(opts)
ExVCR.Mock.mock_methods(recorder, ExVCR.Adapter.IBrowse)
on_exit fn ->
ExVCR.Recorder.save(recorder)
end
:ok
end
defp setup_vcr(%{vcr: true} = context), do: setup_vcr(Map.put(context, :vcr, []))
defp setup_vcr(_), do: :ok
defp normalize_fixture(fixture) do
fixture
|> String.replace(~r/\s/, "_")
|> String.replace("/", "-")
|> String.replace(",", "")
|> String.replace("'", "")
end
end
end
end
I hardcoded the adapter but that should be easy to fix. It would be nicer to build on inject/eject functions but this was a quick workaround.
how hard would it be to refactor it so that the base methods of usage were to call
insert_cassette(conn, fixture
andeject_cassette(conn)
and haveuse_cassette
call to those?You could store the state in the
conn
and require the same one that was returned from insert be passed to eject.So here's why this is cool. Then, I can do things like:
then I can use
setup
/on_exit
to insert/eject based on if that tag is present!Thank you for your consideration. I wouldn't mind doing it myself if you have some input on how you'd like me to do it.