【Rails】有关TDD测试入门

本文介绍如何在Rails项目中使用RSpec进行行为驱动开发(BDD),包括配置RSpec、生成静态页面的集成测试、编写针对具体页面内容的测试案例,并逐步解决测试过程中出现的问题。


1.让 Rails 使用 RSpec 而不用 Test::Unit

rails generate rspec:install


2.为一些静态界面生成集中测试 

$ rails generate integration_test static_pages
      invoke  rspec
      create    spec/requests/static_pages_spec.rb

可以很清楚的看到生成了static_pages_spec.rb这个文件 ,内容如下:

require 'spec_helper'

describe "StaticPages" do
  describe "GET /static_pages" do
    it "works! (now write some real specs)" do
      # Run the generator again with the --webrat flag if you want to use webrat methods/matchers
      get static_pages_index_path
      response.status.should be(200)
    end
  end
end

3.写一个测试首页内容的测试:

require 'spec_helper'

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


4若要测试正确运行,我们要在 spec_helper.rb 中加入一行代码

RSpec.configure do |config|
  .
  .
  .
  config.include Capybara::DSL
end

5.运行测试:

bundle exec rspec spec/requests/static_pages_spec.rb

可以看到我们的测试是失败的,因为首页是系统为我们生成的,不包含测试通过所需要的“Sample App”

将其修改便可以使得测试通过,这就是BDD,行为驱动测试,先写失败的测试,不断改进,使之成功。


如果写一个有关“About”页面的测试,开始提示路由失败,我们添加路由,提示action找不到错误,继续添加action,发现缺少模板,添加相关页面文件,最后测试变绿 


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值