ruby-on-rails - 避免 Rspec + Capybara 中的代码重复

标签 ruby-on-rails rspec capybara

假设我对新输入进行了测试,并在输入无效时对新输入进行了测试(第一个测试是在输入有效的情况下进行的)。

例如(来 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/

相关文章:

ruby - capybara ::dsl::模块的未定义方法 'delegate'

ruby-on-rails - `secret_token` 环境缺少 `secret_key_base` 和 'development',在 `config/secrets.yml` 中设置这些值

ruby - 在测试 HTML 属性是否包含预期 URL 时,如何忽略主机名?

ruby-on-rails - 如何编写一个检查 div 是否为空的 capybara 匹配器?

ruby-on-rails - 在 RSpec 单元测试中模拟竞争条件

ruby-on-rails - rspec Controller 测试中的自定义请求 header 作为 rack.session 传递

ruby-on-rails-3 - 试图让 Selenium 在 Rails 3 中工作 - "WebMock::NetConnectNotAllowedError"

php - 国家名称在数据库中存储为整数/数字是否比包含其名称的字符串更好?

ruby-on-rails - 用于解析序列化 PHP 数组的 ruby​​ gem?

ruby-on-rails - dalli vs memcached gem for heroku 上的 rails 项目