我一直在玩 Elixir/Phoenix 第三方模块。(用于从 3rd 方服务获取一些数据的模块)其中一个模块看起来像这样:
module TwitterService do
@twitter_url "https://api.twitter.com/1.1"
def fetch_tweets(user) do
# The actual code to fetch tweets
HTTPoison.get(@twitter_url)
|> process_response
end
def process_response({:ok, resp}) do
{:ok, Poison.decode! resp}
end
def process_response(_fail), do: {:ok, []}
end
实际数据在我的问题中并不重要。所以现在,我对如何在测试中动态配置@twitter_url
模块变量以使某些测试故意失败很感兴趣。例如:
module TwitterServiceTest
test "Module returns {:ok, []} when Twitter API isn't available"
# I'd like this to be possible ( coming from the world of Rails )
TwitterService.configure(:twitter_url, "new_value") # This line isn't possible
# Now the TwiterService shouldn't get anything from the url
tweets = TwitterService.fetch_tweets("test")
assert {:ok, []} = tweets
end
end
我怎样才能做到这一点?
注意:我知道我可以在和环境中单独:configs
配置,但我也希望能够测试来自 Twitter API 的真实响应,这会改变整个测试环境的 URL。
我想出的解决方案之一是@twiter_url
dev
test
def fetch_tweets(user, opts \\ []) do
_fetch_tweets(user, opts[:fail_on_test] || false)
end
defp _fetch_tweets(user, [fail_on_test: true]) do
# Fails
end
defp _fetch_tweets(user, [fail_on_test: false]) do
# Normal fetching
end
但这似乎很愚蠢和愚蠢,必须有更好的解决方案。