测试 使用 feature Spec 编写用户 / 验收测试

flypiggys · 2013年09月08日 · 最后由 yfractal 回复于 2013年09月09日 · 4753 次阅读

feature spec 与 request spec 的区别 rspec 和 capybara 在 ruby 程序员中很多人都不陌生了。在 2.0 版本以后的 capybara 中,新加入了 feature spec 的写法。在 rspec 中默认使用 spec/feature,而不再使用 spec/request.

feature spec 在测试中来说是比较高等级的测试。大概相当于集成测试或者更高级别的用户/验收测试。一般是模拟用户的实际操作和应用外部的请求来执行测试.简单来说就是模拟浏览器中的动作,期待应用正确的反应。

为什么 2.0 之后的 capybara 要做出这样的改动呢?

因为一般的来说 capybara 是模拟浏览器中的动作,这种测试是相当于模拟一个用户在用户界面中的操作,是基于 usercase 的。而以前的 request spec 则还是没有脱离应用层面 (发送 http 请求,比较相应结果),比如在以前的 capybara 的 dsl 中,使用'get'来访问页面,而现在则改成了'visit'.后者'访问'这个动作,比'get'这个 http 请求更接近于用户的行为。

所以使用 feature spec 相对来说更符合 behavior 的思想,也带来更好的阅读性。

rails 中使用 feature spec 本文以 rails 为例,来介绍 feature spec 的使用。

首先安装 rspec 和 capybara,在 gemfile 中加入

group :development, :test do
   gem 'rspec-rails'
end

group :test do
   gem 'capybara'
end

之后执行

bundle install

再之后执行

rails generate rspec:install

rspec 和 capybara 就安装完毕了。

rails 中的 generator 默认生成的集成测试会在 request/xxxx_spec.rb.默认是不支持 capybara 的,我们如果要在其中使用 capybara 还要在 spec_helper 中的 configure 中加入config.include Capybara::DSL

而我们要使用的 feature/xxxx_spec.rb 目前尚无法由 rails 自动生成,但是不用做任何设置就可以支持 capybara 的 DSL.

所以我们手动建立 spec/feature 文件夹,在其中手动创建 XXXX_spec.rb 的测试文件。

feature spec 写法 在 feature spec 中,我们使用feature - scenario 来替代之前 rspec 的describe - it模式 注意两者千万不要混写成feature - it或者describe - scenario这种不伦不类的风格..

另外与 describe 不同,feature 下面是不允许再套 feature 的。

describe "Static pages" do
  describe "Home page" do
    it "should have the content 'Sample App'" do
      visit '/static_pages/home'
      expect(page).to have_content('Sample App')
    end
  end
end

这样是可以的,但是把 describe 换成 feature 则会报错。

feature spec 的测试中,我们一般按照待测的功能点来划分用例,即每一个 feature.而每一个 scenario 对应一条 user case.这一点和测试人员写测试用例的方法很相似。比如下面的 2 条测试用例

功能点 用户输入 期望结果 用户登录 用户输入正确的用户名和密码 登录成功 用户输入错误的用户名和密码 登录失败

使用 feature spec 的方式写出的测试代码如下。

require "spec_helper"

feature "Login" do
  scenario "User enter right account" do
    visit "/login"

    fill_in "Name", :with => "username"
    fill_in "Password", :with => "right"
    click_button "login"

    expect(page).to have_text("welcome back,username")
  end

  scenario "User enter wrong account" do
    visit "/login"

    fill_in "Name", :with => "username"
    fill_in "Password", :with => "wrong"
    click_button "login"

    expect(page).to have_text("Wrong password,please try again!")
  end

end

feature spec 的简单介绍就写到这里,希望大家喜欢这种方式。

source

feature 之下虽然不能嵌套 feature,但是可以嵌套 context

可不可以说,rspec 自带了黄瓜呢?

需要 登录 后方可回复, 如果你还没有账号请 注册新账号