如何使用大量“have_link"保持 rspec 测试干燥? [英] How to keep rspec tests DRY with lots of "have_link"
问题描述
我是 Ruby on Rails 的新手,我正在做 http://ruby.railstutorial.org现在.
I'm new to Ruby on Rails and I'm doing http://ruby.railstutorial.org right now.
据我所知,该语言应该严格遵循这个 DRY 标准,但在本教程中涉及到测试驱动开发时,它太湿了.
From what I understand the language is supposed to follow this DRY standard wery strictly but it's so WET when it comes to test driven development in this tutorial.
例如
it { should have_link('Users', href: users_path) }
it { should have_link('Profile', href: user_path(user)) }
it { should have_link('Settings', href: edit_user_path(user)) }
it { should have_link('Sign out', href: signout_path) }
这里有很多行看起来几乎一样.
Here we have lots of rows that almost looks the same.
我们试过了
it "should have following links from this array" do
[
['Users', href: users_path],
['Profile', href: user_path(user)],
['Settings', href: edit_user_path(user)],
['Sign out', href: signout_path]
].each { |a| page.should have_link(a[0], a[1]) }
end
此代码有效,但看起来很丑,而且行数更多.
This code works but it's looks ugly and it's more rows.
所以我想知道将数组添加到 has_link 方法是否更好.
So I want to know if it's an better way to add an array to have_link method.
我现在有了一个好主意,但我不知道如何让它发挥作用.
I now have a great idea but I don't know how to make it work.
这是我的帮手(它看起来不像我创建这个问题时所做的.它是在 Michaël Witrant 的回答之后编辑的)
This is my helper (it does not look like it did when i created this question. It is edited after an answer from Michaël Witrant)
RSpec::Matchers.define :have_these_links do |*links|
match do |actual|
links.each do |link|
have_link(link.first, link.extract_options!).matches?(actual)
end
end
end
这现在应该是我的测试
it { should have_these_links(['Users', href: users_path],
['Profile', href: user_path(user)],
['Settings', href: edit_user_path(user)],
['Sign out', href: signout_path]) }
所以这可行,但对用户不友好.当我运行测试并且页面上不存在链接时,它告诉我我没有这些链接.但是我将能够让助手告诉我我缺少哪个链接.这是我的错误代码
So this works but it's not user friendly. When I run the test and I have an link does not exist on the page it tells me that I do not have these links. But I will be able to make the helper tell me which link I'm missing. This is my error code
expected #<Capybara::Session> to have these links ["Users", {:href=>"/users"}], ["Test Link", {:href=>"/Does_not_exist"}], and ["Profile", {:href=>"/users/991"}]
# ./spec/requests/authentication_pages_spec.rb:42:in `block (4 levels) in <top (required)>'
推荐答案
To define custom matchers you can read this feature and some inspiration.
然后写出类似的东西:
RSpec::Matchers.define :have_links do |expected|
match do |actual|
expected.all? do |name, options|
have_link(name, options).matches?(actual)
end
end
end
但是 IMO,您的第一次尝试是最好的编写方式:干净且易于阅读.
But IMO, your first try is the best way to write it: clean and easy to read.
这篇关于如何使用大量“have_link"保持 rspec 测试干燥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!