我有一个 POST 模型、 Controller 和 View ,目前正在创建其测试套件以确保所有内容都经过正确测试。我现在正在创建集成测试,并且在运行“成功编辑帖子”测试时似乎总是遇到相同的错误,表明 ID 丢失。
我真的不明白我做错了什么。错误消息显示缺少 :id 键,但创建新帖子时不应该自动创建一个 :id 键吗?我做错了什么?
版本:
ruby :2.1.2
rails :4.2.1
集成测试
require 'test_helper'
class PostsCrudTest < ActionDispatch::IntegrationTest
def setup
@post = { title: "This is the title",
content: "Detailed comment."*10,
phone: 9991118888,
email: "email@h_list.com",
user_id: users(:spiderman).id }
end
test "creates a new post successfully" do
get new_post_path
assert_template 'posts/new'
assert_difference 'Post.count', 1 do
post posts_path, post: @post
end
assert_template 'posts/show'
end
test "fails to create a new post with inaccurate info" do
get new_post_path
assert_no_difference 'Post.count' do
post posts_path, post: { title: "", content: "", phone: 1111, email: 00 }
end
assert_template 'posts/new'
end
test "shows a new post correctly" do
get new_post_path
post posts_path, post: @post
assert_template 'posts/show'
assert_equal 'Your new posting was created.', flash[:success]
assert_select 'h2', @post[:title]
assert_select 'h2+p', @post[:content]
end
test "edits a post successfully" do
get new_post_path
post posts_url, post: @post
assert_template 'posts/show'
get edit_post_path, post: @post
# assert_select '.edit_post' do
assert_select 'textarea', @post[:content]
# end
end
end
测试结果
$ rake test:integration
Run options: --seed 35902
# Running:
...E
Finished in 0.310827s, 12.8689 runs/s, 32.1722 assertions/s.
1) Error:
PostsCrudTest#test_edits_a_post_successfully:
ActionController::UrlGenerationError: No route matches {:action=>"edit", :controller=>"posts"} missing required keys: [:id]
test/integration/posts_crud_test.rb:44:in `block in <class:PostsCrudTest>'
4 runs, 10 assertions, 0 failures, 1 errors, 0 skips
相关路线:
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
注意:在实际网站上一切似乎都运行良好。只是测试套件给了我这个错误。
最佳答案
The error message says that an :id key is missing
是的,因为您要做两个步骤:
您可以使用@post 哈希创建新帖子。我假设帖子是在服务器上创建的,这通常意味着帖子是在数据库中创建的,并且创建了一个新的 id。
您尝试编辑 @post 哈希,它没有任何 ID。这就是您收到错误消息的原因。
有多种方法可以解决这个问题。
选项 1 很简单:直接在代码中创建帖子,而不是使用 new_post_path。
示例:
test "edits a post successfully" do
p = Post.create(@post) # or whatever options you want
get edit_post_path, post: p.id
...
选项 2 是高级选项:按照您正在执行的操作创建帖子,并让您的服务器返回新创建帖子的 ID。如果需要,您可以将其放入 HTTP 响应中,或者将其放入更具结构性的内容中,例如 JSON 响应。
关于ruby-on-rails - MiniTest - 找不到路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30381356/