I’ve been asked to write a few real life examples of Stubr - in particular, how to set the up the stubs in the first instance.
I think these examples are good illustrations (and are pretty self explanatory):
Random Numbers:
describe "stub :rand" do
test "can stub :rand.uniform/1" do
rand_stub = Stubr.stub!([uniform: fn _ -> 1 end], module: :rand)
assert rand_stub.uniform(4) == 1
end
end
Timex:
describe "stub Timex" do
test "can stub Timex.now/0" do
fixed_time = Timex.to_datetime({2999, 12, 30})
timex_stub = Stubr.stub!([now: fn -> fixed_time end], module: Timex)
assert timex_stub.now == fixed_time
end
test "can stub Timex.now/0 and defer to un-stubbed Timex functions" do
fixed_time = Timex.to_datetime({2999, 12, 30})
timex_stub = Stubr.stub!([now: fn -> fixed_time end], module: Timex, auto_stub: true)
assert timex_stub.before?(fixed_time, timex_stub.shift(fixed_time, days: 1))
end
end
HTTPoison:
describe "stub HTTPoison" do
setup do
http_poison_stub = Stubr.stub!([
get: fn("www.google.com") -> {:ok, %HTTPoison.Response{body: "search", status_code: 200}} end,
get!: fn("www.nasa.com") -> %HTTPoison.Response{body: "space", status_code: 500} end,
post: fn("www.nasa.com", "content") -> {:error, %HTTPoison.Error{id: nil, reason: :econnrefused}} end
], module: HTTPoison)
[stub: http_poison_stub]
end
test "can stub HTTPoison.get/1", context do
{:ok, response} = context[:stub].get("www.google.com")
assert response.body == "search"
assert response.status_code == 200
end
test "can stub HTTPoison.get!/1", context do
response = context[:stub].get!("www.nasa.com")
assert response.body == "space"
assert response.status_code == 500
end
test "can stub HTTPoison.post/1", context do
{:error, error} = context[:stub].post("www.nasa.com", "content")
assert error.id == nil
assert error.reason == :econnrefused
end
end
Find Stubr at