在Capybara功能规格中测试吐司是否会爆炸?

时间:2016-03-14 13:46:44

标签: ruby-on-rails rspec capybara rspec-rails materialize

我有一个Rails应用程序,我最近重构了标准flash [:success]消息以使用flash [:toast],使用http://materializecss.com/dialogs.html

这就是我对我的flash部分所做的事情:

<% flash.each do |type, message| %>
  <% if type == "success" %>
    <div class="alert alert-success alert-dismissable" role="alert">
      ...
    </div>
  <% elsif type == "toast" %>
    <script>
      $(function() {
        Materialize.toast('<%= message %>', 3000);
      });
    </script>
  <% else %>
    <div class="alert alert-danger alert-dismissible" role="alert">
      ...
    </div>
  <% end %>
<% end %>

这很有效,看起来很棒,尤其是在移动设备和复杂的数据页面上,我将用户发送回页面中间,页面顶部的标准Flash成功消息将不可见。< / p>

我可以很容易地测试flash [:toast]在控制器测试中是不是nil,但是在capybara功能测试中,我没有访问权限,而且我不能使用我以前使用的标准代码测试flash [:success]如:

expect(page).to have_content("Your email address has been updated successfully.")
expect(page).to have_css(".alert-success")

现在我正在测试不存在警报危险,例如:

expect(page).to_not have_css(".alert-danger")

这有效,但并没有真正测试吐司被炒掉的情况。有没有办法检查javascript被激活或者吐司出现在页面上3秒钟?

1 个答案:

答案 0 :(得分:3)

只要您使用的是支持JS的驱动程序(除了默认的机架测试驱动程序之外的任何东西),那么

expect(page).to have_content("The message shown by the toast") 

应该在页面上显示toast时找到它。如果你想检查它是否出现并在3秒内消失,你可以做类似

的事情
expect(page).to have_content("The message shown by the toast") 
expect(page).not_to have_content("The message shown by the toast", wait: 3)

第一个语句应该等待文本出现,第二个语句将等待最多3秒钟才能消失。如果您想要实际验证文本是否显示在Toast容器中,那么您可以执行

expect(page).to have_css("#toast-container", text: "The message shown") #update css selector to whatever container you are displaying the toast in
expect(page).not_to have_css("#toast-container", text: "The message shown", wait: 3)
相关问题