gpt4 book ai didi

ruby-on-rails - 测试时无法从 activerecord 检索保存的数据

转载 作者:行者123 更新时间:2023-11-28 21:09:34 25 4
gpt4 key购买 nike

我正在测试 Controller 。 Index just 方法将文章保存到 activerecord 但我无法从测试代码中获取文章。

我错过了什么?

Controller

class ArticlesController < ApplicationController
def create

if Article.new(:title => "abc").save
render status: 200, json: ""
else
render status: 500, json: ""
end

end
end

测试

require 'test_helper'

class ArticlesControllerTest < ActionController::TestCase
test "should get create" do
get :create
assert_response :success
assert_nil Article.where(title: "abc"), "Article nil"

end

end

我得到以下结果

F

Finished in 0.100930s, 9.9079 runs/s, 19.8157 assertions/s.

1) Failure:
ArticlesControllerTest#test_should_get_index [test/controllers/articles_controller_test.rb:7]:
Article nil.
Expected #<ActiveRecord::Relation [#<Article id: 980190963, title: "abc", created_at: "2016-06-24 13:23:36", updated_at: "2016-06-24 13:23:36">]> to be nil.

1 runs, 2 assertions, 1 failures, 0 errors, 0 skips

最佳答案

您实际上正在接收创建的文章记录。查看测试输出的最后一行。它显示“Expected #ActiveRecord...”,这意味着它返回了一个 Article 对象,但它应该不返回任何东西(nil)。

测试代码的问题在于断言行。 assert_nil 是在这种情况下使用的错误方法。

尝试这样的事情:

assert_equal "abc", Article.first.title

关于ruby-on-rails - 测试时无法从 activerecord 检索保存的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38014659/

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