使用水豚和 rails3 进行 Rspec 视图测试 [英] Rspec view testing with capybara and rails3
问题描述
我真的很喜欢 RSpec 能够分离控制器和视图测试的方式,但在让水豚匹配器在视图测试中工作时遇到了一些问题.我基本上试图实现的是这样的:
I really like the way RSpec is able to separate controller and view tests but have some problems with getting capybara matchers to work in a view test. What i basically try to achieve is sth like this:
describe "some page" do
it "should render with lots of stuff" do
assign ..
render
rendered.should have_button ('Any button') #or any capybara matcher, really
end
end
我在网上看到了一些帖子,展示了如何配置水豚和 rails3 以与黄瓜或 rspec 控制器测试顺利工作,但这并不是我真正想要的 - 也就是说,在尽可能低的级别测试视图.
I've seen some posts on the net showing how to configure capybara and rails3 to work smoothly with cucumber or rspec controller tests, but this is not really what I want - that is, testing the views at the lowest level possible.
此外,如果有另一种方法可以做到这一点(不需要大量自定义代码,因为我知道我可以编写一些匹配器,使用 nokogiri 或任何合适的工具从渲染中提取给定的选择器)那也很棒 - 使用水豚不是必需的.
Also if there's another way to do this (not requiring lots of custom code, couse I know i could write some matchers that extract given selectors from rendered using nokogiri or whatever tool suitable) that'd be great too - using capybara is not a requirement.
推荐答案
现在可以选择在测试控制器(以及视图)时使用 Capybara 匹配器(没有 Webrat 包).我是这样使用的:
There is now an option to use Capybara matchers (without Webrat baggage) when testing controllers (and views too). I'm using it this way:
describe GlobalizeTranslationsController do
render_views
let(:page) { Capybara::Node::Simple.new(@response.body) }
describe "PUT :update" do
before do
put :update
end
it "displays a flash notice" do
page.should have_selector('p.notice')
end
end
end
完整代码:
参考文献:
- http://robots.Thoughtbot.com/post/8087279685/use-capybara-on-any-html-fragment-or-page
- http://cakebaker.42dh.com/2010/09/19/cucumber-switching-from-webrat-to-capybara/
- http://trevorturk.com/2010/12/22/using-capybara-without-cucumber-in-rails-3
这篇关于使用水豚和 rails3 进行 Rspec 视图测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!