如何为ActiveRecord编写规范

时间:2012-02-28 07:17:22

标签: ruby-on-rails specifications

我的规格/型号代码为'spec_helper'

describe Student do
   it "should be work" do
     student = Student.find 1
     puts student.version
   end
end

运行代码时会显示以下错误..,

Failures:

  1) Student should be work
     Failure/Error: student = Student.find 2
     ActiveRecord::StatementInvalid:
       Could not find table 'students'
     # ./spec/models/student_spec.rb:6:in `block (2 levels) in <top (require


Finished in 0.00109 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/models/student_spec.rb:4 # Student should be work

我有学生桌。另外,我正在使用paper_trail gem。 运行rake db:test:prepare然后它显示错误为。,

Failures:

  1) Student should be work
     Failure/Error: s = Student.find 1
     ActiveRecord::RecordNotFound:
       Couldn't find Student with id=1
     # ./models/student_spec.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.02182 seconds
1 example, 1 failure

Failed examples:

rspec ./models/student_spec.rb:4 # Student should be work

3 个答案:

答案 0 :(得分:1)

在测试环境中似乎没有表学生,尝试运行 $ bundle exec rake db:test:prepare

答案 1 :(得分:0)

您是否在测试数据库中传播了一些数据(使用fixture或类似FactoryGirl gem的东西)? 否则你不会在你的数据库中找到任何“学生”。

Test-DB和Development DB没有任何共同之处。实际上,每次测试都会清除Test-DB。

答案 2 :(得分:0)

问题是测试数据库的学生表中没有带id = 1的学生(测试数据库在开始新测试之前被清除)。 你想测试什么?

也许你想在规范的开头使用before来插入学生:

describe Student do
  before do
    @student = Student.new(:version => 15)
    @student.save
  end

  it "should be work" do
    student = Student.first
    # Test something ...
  end
end

在每次测试之前运行之前的块,在这种情况下,您可以获得(测试)数据库中的第一个学生,因为您将其插入到前一个块中(但我不知道您要测试的是什么,如果确实需要保存学生。)