假设我对新输入进行了测试,并在输入无效时对新输入进行了测试(第一个测试是在输入有效的情况下进行的)。
例如(来 self 的代码):
scenario "valid input saving" do
visit program_stream_path(@program, @stream)
click_link "#link"
fill_in "#fill_in", :with=>"1"
click_button "Next"
expect(page).to have_current_path new_students_list_stream_path(@stream)
within("#student_0") do
fill_in "Имя", :with => "Name"
fill_in "Фамилия", :with => "Surname"
fill_in "Электронная почта", :with => "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4032212e242f2d2d21292c002d21292c6e232f2d" rel="noreferrer noopener nofollow">[email protected]</a>"
end
print page.html
click_button "Save"
expect(page).to have_current_path program_stream_path(@program, @stream)
#...other code
end
显然,检查无效输入行为的测试重复了这一部分:
scenario "invalid input leads to correct input page" do
visit program_stream_path(@program, @stream)
click_link "#link"
fill_in "#fill_in", :with=>"1"
click_button "Next"
expect(page).to have_current_path new_students_list_stream_path(@stream)
#other code
如何避免这种复制粘贴方式?
最佳答案
你可以在这种情况下使用 before block
feature "..." do
before :each do
visit program_stream_path(@program, @stream)
click_link "#link"
fill_in "#fill_in", :with=>"1"
click_button "Next"
expect(page).to have_current_path new_students_list_stream_path(@stream)
end
scenario "valid input saving"
#unique code for this scenario
end
scenario "invalid input leads to correct input page"
# unique code for this scenario
end
end
如果想要/需要,外部功能 block 可以是描述或场景 block ,因为您可以嵌套多个级别。如果您需要在多个功能文件中使用代码,那么将其移动到规范帮助程序文件之一中的方法是有意义的。
关于ruby-on-rails - 避免 Rspec + Capybara 中的代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34567646/