Rspec 3.X:原生内置的html匹配器?或者我们必须使用Capybara?

时间:2015-06-23 07:58:22

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

随着Rspec的发展,我已经阅读了大量关于所有变化的文档和SO问题/答案,想要确定答案......

我的目标是使用原生Rspec-rails(我有3.2.2)进行集成控制器/视图测试,寻找1)CSS类和2)ID选择器。换句话说这个视图片段:

<!-- staticpages/dashboard -->
<div class="hidden">Something</div>
<div id="creation">This</div>

这应该通过(但应该在语义上写):

describe StaticpagesController do
  render_views

  it "should find everything" do
    get :dashboard
    expect(response.body).to have_selector("div#creation")
    expect(response.body).to have_css("hidden")
    expect(response.body).to_not have_selector("div#nothinghere")
  end
end

我想在没有像Capybara这样的额外宝石的情况下这样做;那可能吗?

这是我迄今为止所学到的高水平:

在我自己的实验中,上面的代码生成了:

Expect<long response.body here>.to respond to `has_selector?`

所以确实已经弃用了。尽管如此,我还是想知道是否有其他方法可以做到这一点,我不知道。

如果事实证明我需要Capybara做这些花哨的匹配器,有没有办法在我的集成控制器/视图规格中执行此操作?我的理解是,我必须将type: :feature添加到describe StaticpagesController行才能使用Capybara的匹配器。但是,当我这样做时,render_views不再可用(因为它仅限于type: :controller)。请注意,如果按照此帖(https://www.relishapp.com/rspec/rspec-rails/v/2-99/docs/controller-specs/use-of-capybara-in-controller-specs),我手动render_views进入我的控制器规范,include Capybara::DSL也会死亡。无论如何,我真的不想将我当前的控制器规格改写成一堆功能规格......

1 个答案:

答案 0 :(得分:0)

您希望功能规格(使用Capybara)比控制器规格更多you're not testing any of the things controller specs are typically used to test,例如:

  • 是否呈现模板
  • 是否发生重定向
  • 在控制器中分配了哪些实例变量以与视图共享
  • 通过回复发回的Cookie

此外,您可能需要考虑为控制器规范编写新应用程序的功能规范,因为controller tests will probably be dropped in Rails 5支持编写集成/功能测试。

有关您可以编写的不同类型规范的描述,以及它们通常用于哪些规范, 见this SO answer