gpt4 book ai didi

ruby-on-rails - MiniTest - 找不到路由

转载 作者:数据小太阳 更新时间:2023-10-29 09:03:11 25 4
gpt4 key购买 nike

我有一个 POST 模型、 Controller 和 View ,我目前正在创建它的测试套件以确保所有内容都经过正确测试。我现在正在创建集成测试,并且似乎总是遇到相同的错误,即在运行“成功编辑帖子”测试时,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

是的,因为您正在执行两个步骤:

  1. 您使用@post 散列创建了一个新帖子。我假设帖子是在服务器上创建的,这通常意味着帖子是在数据库中创建的,并且会创建一个新的 ID。

  2. 您尝试编辑没有任何 ID 的 @post 散列。这就是您收到错误消息的原因。

有多种选择可以解决这个问题。

选项 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com