Skip to content

Commit 6d82912

Browse files
richjosevalim
authored andcommitted
Allow variables defined in doctests to be used in expectation (#12730)
1 parent 785c292 commit 6d82912

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

lib/ex_unit/lib/ex_unit/doc_test.ex

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -382,9 +382,15 @@ defmodule ExUnit.DocTest do
382382
last_expr = Macro.to_string(last_expr(expr_ast))
383383

384384
quote do
385+
# `expr_ast` may introduce variables that may be
386+
# used within `expected_ast` so they both need to
387+
# unquoted together here
388+
value = unquote(expr_ast)
389+
expected_value = unquote(expected_ast)
390+
385391
ExUnit.DocTest.__test__(
386-
unquote(expr_ast),
387-
unquote(expected_ast),
392+
value,
393+
expected_value,
388394
unquote(doctest),
389395
unquote(last_expr),
390396
unquote(expected),

lib/ex_unit/test/ex_unit/doc_test_test.exs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,16 @@ defmodule ExUnit.DocTestTest.Haiku do
443443
end
444444
|> ExUnit.BeamHelpers.write_beam()
445445

446+
defmodule ExUnit.DocTestTest.VariableInExpectation do
447+
@doc """
448+
iex> num = 1
449+
iex> ExUnit.DocTestTest.VariableInExpectation.inc(num)
450+
num + 1
451+
"""
452+
def inc(num), do: num + 1
453+
end
454+
|> ExUnit.BeamHelpers.write_beam()
455+
446456
defmodule ExUnit.DocTestTest.PatternMatching do
447457
def starting_line, do: __ENV__.line + 2
448458

@@ -506,6 +516,7 @@ defmodule ExUnit.DocTestTest do
506516
doctest ExUnit.DocTestTest.IndentationHeredocs
507517
doctest ExUnit.DocTestTest.FencedHeredocs
508518
doctest ExUnit.DocTestTest.Haiku
519+
doctest ExUnit.DocTestTest.VariableInExpectation
509520

510521
import ExUnit.CaptureIO
511522

0 commit comments

Comments
 (0)