新手问题 Rails Model test 问题

tank_lei · 2013年10月18日 · 最后由 tank_lei 回复于 2013年10月18日 · 1848 次阅读

这里用的是 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

别的配置就没有修改

我的问题如下:

  1. 这两条数据从何而来?
  2. 我的数据为什么无法插入数据库?

你看一下你的 test/fixtures/posts.yml 这两条是从那里来的

#1 楼 @ZombieCoder 原来如此!我删除了!但执行测试方法的时候,数据还是无法插入,还有哪的配置没有修改吗?

用 test 环境程序跑的前后会自动清数据 就是所以你在跑完后去看数据里是没有你存入的数据的 只要你的 should_save 通过就可以了

#3 楼 @ZombieCoder 哦,原来如此,我说打印的时候,有 id 显示,但数据库没有数据呢!好的,谢谢阿!

需要 登录 后方可回复, 如果你还没有账号请 注册新账号