我们要把应用各组件放在一起做集成 测试,这样才能保证模型和控制器之间能够良好契合。
在 RSpec 中,这种测试称为功能测试(feature spec),有时也称为验收测试(acceptance test)或集成测试(integration test)。这种测试的作用是确保 软件作为一个整体能按预期使用。
Capybara库 (8000star),用来定义功能测试的步骤,模拟真实用户的使用过程。 5.1已经自带这个库,因为系统测试依赖它。
Rails5.1 框架增加了系统测试。用的是MiniTest.
作者喜欢使用Rspec开发Rails应用。
在spec/rails_helper.rb中加入 require 'capybara/rspec'
6.3 一个简单的功能测试
bin/rails generate rspec:feature projects
feature test 和controller test 的区别:控制器测试绕过用户界面,直接把参数发给controller actions.
用到了expect{}.to , scenario作用等同于it。
6.2 Capybara DSL
除了 ,click_link, fill_in, with, click_button还有很多方法。
选择符还可以限定范围,让 Capybara 在页面的某一部分中(within)查找指定的元素。假设有如下的 HTML:
<div id="node">
<a href="http://nodejs.org">click here!</a>
</div>
<div id="rails">
<a href="http://rubyonrails.org">click here!</a> </div>
我们可以像下面这样指明点击哪个“click here!”链接:
within "#rails" do
click_link "click here~!"
end
此外,还可以使用 Capybara 提供的多个 find 方法找出特定元素及其值。例如:
language = find_field("Programming language").value expect(language).to eq "Ruby"
find("#fine_print").find("#disclaimer").click find_button("Publish").click
以上是我最常使用的 Capybara 方法 ,完整方法见Capybara DSL 文档。
6.5调试feature test
save_and_open_page,保存并打开出错的页面。需要手动打开open tmp/...。
安装gem 'launchy'后可以自动打开保存的HTML文件。
测试完成后,应当在提交版本控制之前,把不需要的save_and_open_page删除。
6.6测试JavaScript交互
bin/rails g rspec:feature tasks
be_completed 匹配器matcher :
js:true选项传给scenario,Capybara默认带JS驱动。
然后变更运行浏览器,换为Chrome.
配置:
1. spec/rails_helper.rb中把下面一行注释去掉,
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
2. 创建文件 spec/support/capybara.rb,并写如:
Capybara.javascript_driver = :selenium_chrome
3. 安装ChromeDriver.需要看
见 ChromeDriver 官方文档。
如果安装了brew,则敲击brew install chromedriver
出现提示:
安装提示安装,成功。
运行bin/rspec spec/features/tasks_spec.rb,弹出chrome窗口,我们的应用在这个窗口加载,自动点击连接填写表单自动,完成任务,测试成功,