【发布时间】:2018-05-30 11:45:11
【问题描述】:
我一直在玩 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
我怎样才能做到这一点?
注意: 我知道我可以在dev 和test 环境中分别使用:configs 来配置@twiter_url,但我希望能够根据来自Twitter 的真实响应进行测试API 也是如此,这会改变整个测试环境的 URL。
我想出的解决方案之一是
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
但这看起来很老套和愚蠢,必须有更好的解决方案。
【问题讨论】:
标签: testing elixir phoenix-framework httpoison