【发布时间】:2018-02-04 20:39:32
【问题描述】:
我想测试页面上的每个链接是否返回特定的状态代码。我有一个工作测试,如下所示:
it "does not throw 400/500 error for any link" do
visit '/'
within(".wrapper") do
all('a').each do |link|
http_status = Faraday.head(link[:href].to_s).status
puts "#{link.text}, #{http_status}"
expect((400..500)).not_to include(http_status)
end
end
但是,这对于输出来说非常糟糕,因为所有链接都在一个测试中检查(因此测试中的 puts 会告诉我哪个链接破坏了测试)。我希望能够对每个链接进行单独的测试,而无需为页面上的每个链接手动编写测试。
我试过了:
context "does not throw 400/500 error for any link" do
visit '/'
within(".wrapper") do
all('a').each do |link|
it "does not throw 400/500 error for #{link}" do
link_status_code_is_not(link, (400..500))
end
end
end
end
得到了这个错误
`visit` is not available on an example group (e.g. a `describe` or
`context` block). It is only available from within individual examples
(e.g. `it` blocks) or from constructs that run in the scope of an
example (e.g. `before`, `let`, etc).
所以我尝试将访问移至 before 钩子,但遇到了与 inside 块相同的问题(我无法真正移动)。我已经能够在茉莉花中做这样的事情,但我似乎无法在 rspec 中找到一种方法。
tl:博士;有什么办法可以将 it 块放在 rspec 的循环中?
【问题讨论】:
-
This 可能会对您有所帮助。如果您使用描述块而不是上下文块,似乎可以做到这一点。
-
我一直这样做。为什么你不能在
it块中使用visit? -
@SteveTurczyn 我可以在 it 块内进行访问,但这不是问题。我正在尝试将除 http 状态检查之外的所有内容移到 it 块之外,以便页面上的每个链接都有一个新的 it 块。
-
有多少链接?与其这样做,不如直接制作一个链接名称为
string的数组,这样会更有用。 -
@Rhunal 我将如何收集这些链接?我不能在 it 块之外使用访问或使用功能。我可以尝试直接使用 selenium 从页面读取数据,然后对其进行测试,但这似乎是错误的做法。我很惊讶在 rspec 中没有一种简单的方法可以做到这一点。我可以很容易地用茉莉花做类似的事情。