这里用的是 rails 自带的测试,暂不考虑 RSpec
#post.rb
class Post < ActiveRecord::Base
validates :title, presence: true,
length: { minimum: 5 }
end
#post_test.rb
require 'test_helper'
class PostTest < ActiveSupport::TestCase
test "should_save" do
@post = Post.new(:title => "testtes")
@post.save
puts @post.id
assert @post #@post.save
end
test "should report error" do
# some_undefined_variable is not defined elsewhere in the test case
some_undefined_variable
assert true
end
end
首先,我执行 rake test test/models/post_test.rb test_should_report_error 的时候,会正常显示错误。 当我查看数据库的时候,会发现有两条数据:
mysql> select * from posts;
+-----------+----------+--------+---------------------+---------------------+
| id | title | text | created_at | updated_at |
+-----------+----------+--------+---------------------+---------------------+
| 298486374 | MyString | MyText | 2013-10-18 01:26:28 | 2013-10-18 01:26:28 |
| 980190962 | MyString | MyText | 2013-10-18 01:26:28 | 2013-10-18 01:26:28 |
+-----------+----------+--------+---------------------+---------------------+
2 rows in set (0.00 sec)
不知道这两条数据是怎么来的, 后面当我执行:rake test test/models/post_test.rb test_should_save 的时候,没有报错,但数据库里没有插入数据 始终是上面两条数据的 创建时间和更新时间在变换,puts @post.id 的时候 输出的是 980190962 这个 id 哪里有问题?
我的 model 是通过 rails generate model Post title:string text:text 生成的 数据库配置:
development:
adapter: mysql2
database: blog
pool: 5
timeout: 5000
username: root
password: root
test:
adapter: mysql2
database: blog_test
pool: 5
timeout: 5000
username: root
password: root
production:
adapter: mysql2
database: blog
pool: 5
timeout: 5000
username: root
password: root
别的配置就没有修改