【Rails】有关TDD测试入门



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这个文件内容如下:

  1. require'spec_helper'
  2. describe"StaticPages"do
  3. describe"GET/static_pages"do
  4. it"works!(Nowwritesomerealspecs)"do
  5. #Runthegeneratoragainwiththe--webratflagifyouwanttousewebratmethods/matchers
  6. getstatic_pages_index_path
  7. response.status.shouldbe(200)
  8. end
  9. end
  10. end

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

  1. require'spec_helper'
  2. describe"Staticpages"do
  3. describe"Homepage"do
  4. it"shouldhavethecontent'SampleApp'"do
  5. visit'/static_pages/home'
  6. expect(page).tohave_content('SampleApp')
  7. end
  8. end
  9. end


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

  1. RSpec.configuredo|config|
  2. .
  3. .
  4. .
  5. config.includeCapybara::DSL
  6. end

5.运行测试:

bundle exec rspec spec/requests/static_pages_spec.rb

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

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


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

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...