我正在编写一个rspec / capybara测试,确保表单中的输入字段显示正确的验证。
我担心我的代码不太可读。我怎样才能重构这一点以确保它的可读性?
describe "#page" do
context "form validation" do
1.upto(4) do |index|
it "throws correct validation error when #{5-index} field(s) is (are) empty" do
login(page_path)
fill_in_form(index)
find('.button').trigger(:click)
expect(all('.form-error').count).to eq 5-index
all('.form-error')[-1...index-5].each do |error|
expect(error.text).to eq "#{@inputs[5-index][:error_message]} is required"
end
end
end
end
end
def fill_in_form(number_of_fields)
(0).upto(number_of_fields-1) do |i|
fill_in(@inputs[i][:name], :with => (@inputs[i][:value]))
end
end
def login(path)
visit(path)
# redirected to login
acceptance_login(@user)
visit(path)
# input fields
@inputs = [
{name: 'first_name', error_message: "First name is not valid", value: "John"},
{name: 'last_name', error_message: "Last name is not valid", value: "Doe"},
{name: 'company', error_message: "Company name is not valid", value: "My company"},
{name: 'role', error_message: "Role is not valid", value: "Developer"},
{name: 'phone', error_message: "Phone number is not valid", value: "(800) 492-1111"}
]
end
答案 0 :(得分:1)
您可以将登录内容分成前一个块,添加一些额外的换行符会立即产生差异。
重新考虑在所有这些时间循环遍历表单的需要。功能测试既昂贵又缓慢,因此请将它们用作概述,以确保在表单上实现错误处理。
错误消息的具体实现,在所有相关情况下,我会留下单元测试,因为它们更快,更便宜。这样,您的功能测试就会变得不那么脆弱,如果需要,更容易更改消息。