简体   繁体   English

Ruby on Rails2.3.8:单元测试:Rails / Ruby已设置为在每次测试之前运行。 在所有测试之前运行的方法呢?

[英]Ruby on Rails2.3.8: Unit Testing: Rails/Ruby has setup to run before each test. What about a method that runs before all tests?

I'd like to init the data base once everytime i run tests, rather than every test. 我想每次运行测试而不是每次测试都初始化数据库。 I know with Rspec there is before(:all), but I haven't been able to get that working. 我知道使用Rspec可以使用before(:all),但是我无法使其正常运行。 I was wondering if rails had something similar. 我想知道rails是否有类似的东西。

Firstly: there used to be a before(:all) equivalent in Test::Unit but it was removed (don't know why). 首先:在Test :: Unit中曾经有一个before(:all)等效项,但是它被删除了(不知道为什么)。

Secondly: there are very good reasons not to do what you are trying to do - tests are meant to be run independently of one another, not rely on state that's in the db. 其次:有很好的理由不做您想做的事情-测试是要彼此独立运行,而不是依赖于数据库中的状态。 This way you can guarantee that it's testing exactly what you are expecting it to test. 这样,您可以保证它正在正确测试您期望的测试。

If you have one test that changes the state of the db, and you move it and it runs after another test which expects it to be another state - you run into problems. 如果您有一个测试会更改数据库的状态,然后将其移动并在另一个测试(它期望它是另一种状态)之后运行,则可能会遇到问题。 Thus, all test must be independent. 因此,所有测试必须独立。

Thus: the db is rolled back to its pristine state and re-seeded every time. 因此:db回滚到其原始状态,并且每次都重新播种。

If you really want some state that the db is always in - then set it up in the fixtures... and just realise that the db will be re-loaded for each test. 如果您真的想知道数据库始终处于运行状态,请在固定装置中进行设置...,然后意识到每次测试都会重新加载数据库。

If you are having trouble with load-times... then consider figuring out some other way around the problem - eg don't use huge numbers of fixtures, instead use Factories to only create the data that you need for each individual test. 如果您在加载时间上遇到麻烦...,请考虑解决该问题的其他方法-例如,不要使用大量的夹具,而应使用工厂仅创建每个测试所需的数据。

If there's some other reason... let us know - we may have a solution for it. 如果还有其他原因,请告诉我们-我们可能有解决方案。

Edit: if you really need it, I actually wrote a monkey patch for this a long while back: "faking startup and shutdown" 编辑:如果您真的需要它,我很久以前就为此写了一个猴子补丁: “伪造启动和关闭”

All things to run before everything just go in the top of the class 万事俱备,一切皆有可能

require 'test_helper'

class ObjectTest < ActiveSupport::TestCase
  call_rake("db:bootstrap RAILS_ENV=test")

  #set up our user for doing all our tests (this person is very busy)  
  @user = Factory(:user)
  @account = Factory(:account)    
  @user.account = @account
  @user.save

  # make sure our user and account got created 
  puts "||||||||||||||||||||||||||||||||||||||||||||||"
  puts "| propsal_test.rb"
  puts "|      #{@user.name}"
  puts "|      #{@user.account.name}"
  puts "||||||||||||||||||||||||||||||||||||||||||||||"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM