对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,在没有修改路由设置的情况下,就不需要重启spork了。
对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 { }"有个参数值,默认是:each,其中的代码块会多次执行,对应的后面有几个example,就执行几次,而且,每次执行完,都会清空测试数据库
,就是测完一个example,接着就清空测试数据库,然后测下一个example。
如果这样指定,before(:all) do end 或者 before(:all) { },其中的代码块只会执行一次。