简体   繁体   English

在Ruby on Rails中运行rake测试时出错

[英]Error when I run rake test in Ruby on Rails

I am getting an error when I try to run a test on my very simple app in ROR. 当我尝试在非常简单的ROR应用中运行测试时出现错误。 I am taking a course online and I have this very simple database that has two tables: posts (with title and body ) and comments (with ForeignKey: post_id and body . When I run rake test I get the following error: 我正在在线学习课程,并且我有一个非常简单的数据库,该数据库有两个表: posts (带有titlebody )和comments (带有ForeignKey: post_idbody在运行rake test出现以下错误:

Error: PostsControllerTest#test_should_destroy_post:
ActiveRecord::InvalidForeignKey: SQLite3::ConstraintException: FOREIGN
 KEY constraint failed: DELETE FROM "posts" WHERE "posts"."id" = ?
     app/controllers/posts_controller.rb:57:in `destroy'
     test/controllers/posts_controller_test.rb:43:in `block (2 levels) in <class:PostsControllerTest>'
     test/controllers/posts_controller_test.rb:42:in `block in <class:PostsControllerTest>'


bin/rails test test/controllers/posts_controller_test.rb:41

....

Finished in 12.539965s, 1.1164 runs/s, 1.2759 assertions/s. 14 runs,
16 assertions, 0 failures, 1 errors, 0 skips`

Any help would be appreciated. 任何帮助,将不胜感激。 Thanks. 谢谢。

This error occurs when you delete a row in a table whose primary key is referenced in another table. 当您删除其主键在另一个表中引用的表中的行时,会发生此错误。 You can include ON DELETE CASCADE in your foreign key definition (where you define where the primary key is referenced by another table), or add another delete statement to delete the row referencing the primary key, before doing the delete statement you are currently doing. 您可以在外键定义中包括ON DELETE CASCADE (在其中定义另一个表引用主键的位置),或者添加另一个delete语句以删除引用主键的行,然后再执行当前正在执行的delete语句。

Add this to your Post model: 将此添加到您的Post模型:

has_many :comments, dependent: :destroy

This will destroy associated comments when you will destroy your Post model. 当您破坏Post模型时,这将破坏相关的注释。 So you will not get ConstraintException . 因此,您将不会获得ConstraintException

You can find more info about Rails associations here . 您可以在此处找到有关Rails关联的更多信息。

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

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