码迷,mamicode.com
首页 > 其他好文 > 详细

对rspec的“才知道”

时间:2014-05-21 13:34:09      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:rspec   spork   rails测试   test   

对rspec没有系统的学习,所以总是“才知道”!

才知道

config/environments/test.rb文件中有两行代码很重要

  # The test environment is used exclusively to run your application's
  # test suite. You never need to work with it otherwise. Remember that
  # your test database is "scratch space" for the test suite and is wiped
  # and recreated between test runs. Don't rely on the data there!
  config.cache_classes = true
默认为true,每测完一个example,自动清空数据库。当设置为false的时候,测试时不会自动清空测试数据库数据,我吃过这个亏,测试不通过,

总是报Record ValidatesXXXX already used之类的错误提示。

  # Do not eager load code on boot. This avoids loading your whole application
  # just for the purpose of running a single test. If you are using a tool that
  # preloads Rails for running tests, you may have to set it to true.
  config.eager_load = true
默认是false,测试时不会自动重新载入代码,尤其在使用一些辅助测试的工具时,特别有关系。

我用的spork,当时修改了一个model的约束关系,测试时愣是过不去,看来看去,没想到是spork的问题,当时config.eager_load是默认值false,

于是重启spork后,就ok了,如果把config.eager_load设置为true,就无需重启了。

对rspec很多的语法还不知道怎么用,就知道点浅薄的。

这里有个rspec rails 3.0的介绍https://www.relishapp.com/rspec/rspec-rails/v/3-0/docs

才知道

factories.rb  中定义  companyadmin 和  identity0

  factory :companyadmin, class: User do
    userID      "admin"
    username    "admin"
    password    "123456"
    password_confirmation "123456"
    email "example@qq.com"
    company_id 1
    identity_id 2
  end
  factory :identity0, class: Identity do
    no 0
    identity "系统管理员"
  end
测试时写

let(:companyadmin) { FactoryGirl.create(:companyadmin) }
这句在测试数据中,只算上是new了一个User对象,并没有执行save,此时数据库中并不会新增一条记录

let(:identity0) { FactoryGirl.create(:identity0) }
这一句也就相当于  Identity.new  ,但是我的测试中需要系统管理员身份 这一条存在于测试数据库的数据,

存在了,测试才能通过,于是我在before 里加了一句

before { identity0.save }


才知道

”before do    end“ 或者 ”before {    }" 中的代码块会多次执行,对应的后面有几个example,就执行几次,而且,每次执行完,都会清空测试数据库

,就是测完一个example,接着就清空测试数据库,然后测下一个example。

对rspec的“才知道”,布布扣,bubuko.com

对rspec的“才知道”

标签:rspec   spork   rails测试   test   

原文地址:http://blog.csdn.net/beslow/article/details/26444525

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!