rails 的测试的 bug 当你的 model 的 after_create 中有raise 时

阅读更多
app/models/part.rb

class Part < ActiveRecord::Base
  def after_create
    raise "no way" if self.name == "test"
  end
end


app/controllers/parts_controller.rb

class PartsController < ApplicationController
  def test
    Part.create!(:name => "test")
  end
end


test/functional/parts_controller_test.rb

require File.dirname(__FILE__) + '/../test_helper'

class PartsControllerTest < ActionController::TestCase
  def test_test
    old_count = Part.count
    post :test rescue nil   
    assert_equal(old_count, Part.count)
  end
end


    ruby test\functional\parts_controller_test.rb


结果是

<2> expected but was
<3>.


日志是
Processing PartsController#test (for 0.0.0.0 at 2008-05-01 16:26:57) [POST]
  Session ID: 
  Parameters: {"action"=>"test", "controller"=>"parts"}
  Part Create (0.000000)   INSERT INTO parts ("name", "updated_at", "created_at") VALUES('test', '2008-05-01 16:26:57', '2008-05-01 16:26:57')
  SQL (0.000000)   SELECT count(*) AS count_all FROM parts 

看到没. 居然没有 回滚

换用集成测试
test/integration/model_hg_test.rb
require "#{File.dirname(__FILE__)}/../test_helper"

class ModelHgTest < ActionController::IntegrationTest
  fixtures :parts

  def test_truth
    old_count = Part.count
    
    puts Part.find_by_sql("select * from parts").collect(&:id).join(", ")
    puts Part.find_by_sql("select * from parts").collect(&:name).join(", ")
    
    post '/parts/test'
    
    puts Part.find_by_sql("select * from parts").collect(&:id).join(", ")
    puts Part.find_by_sql("select * from parts").collect(&:name).join(", ")
    
    assert_equal(old_count, Part.count)
    
  end
end


结果是


D:\t1\t1>ruby test\integration\model_hg_test.rb
Loaded suite test/integration/model_hg_test
Started
953125641, 996332877
MyString, MyString
953125641, 996332877, 996332878
MyString, MyString, test
F
Finished in 1.281 seconds.

  1) Failure:
test_truth(ModelHgTest)
    [test/integration/model_hg_test.rb:17:in `test_truth'
     E:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/actionpack-2.0.2/lib/action_controller/integration.rb:547:in `
']:
<2> expected but was
<3>.

1 tests, 1 assertions, 1 failures, 0 errors


没有 回滚

狂汗!!!

你可能感兴趣的:(Rails,Ruby,MySQL,SQL,SQLite)