简体   繁体   中英

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. 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:

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.

Add this to your Post model:

has_many :comments, dependent: :destroy

This will destroy associated comments when you will destroy your Post model. So you will not get ConstraintException .

You can find more info about Rails associations here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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