【问题标题】:Rspec does not see my active record modelsRspec 看不到我的活动记录模型
【发布时间】:2021-05-31 13:00:38
【问题描述】:

我对 Rspec 还是很陌生。我正在使用 Rails 6。我为 Rspec 添加了以下 gem,并为 rspec 运行了安装命令。

 gem 'rspec-rails'
 gem 'rexml'

我创建了一个如下所示的 spec/models/post_spec.rb 文件:

require 'rails_helper'

RSpec.describe Post, type: :model do

  it "doesn't create a post without a title" do
    Post.new(title: "", body: "weqwe").save
  end
end

当我运行 rspec 时出现以下错误

NoMethodError:
       undefined method `post' for #<Post id: nil, title: "", body: "weqwe", created_at: nil, updated_at: nil>

我玩过代码,但每当我尝试使用 Active Record 做某事时,它都会中断。

另外,如果它有帮助,运行 rails test 不会接受我的任何测试。

编辑:这是完整的错误

An error occurred while loading ./spec/models/post_spec.rb.
Failure/Error: Post.create({title: "something", body: "something"})

NoMethodError:
  undefined method `post' for #<Post id: nil, title: "something", body: "something", created_at: nil, updated_at: nil>
# ./spec/models/post_spec.rb:5:in `block (2 levels) in <main>'
# ./spec/models/post_spec.rb:4:in `block in <main>'
# ./spec/models/post_spec.rb:3:in `<main>'
# /Users/mymac/.rvm/gems/ruby-3.0.0/gems/bootsnap-1.7.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:59:in `load'
# /Users/mymac/.rvm/gems/ruby-3.0.0/gems/bootsnap-1.7.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:59:in `load'


Finished in 0.00007 seconds (files took 6.23 seconds to load)
0 examples, 0 failures, 1 error occurred outside of examples

【问题讨论】:

  • 您是否创建了测试数据库?
  • "db:create" 没有设置 env 创建开发数据库,​​而不是测试,尽管 iirc db:test:prepare 应该创建测试数据库并在它缺少迁移时赚取。您应该包括整个堆栈跟踪 - 错误表示缺少字段或编码错误。
  • “帖子”表是什么样的?是不是叫做“帖子”?
  • 太棒了;很高兴你解决了。
  • 无关,但请不要添加问题的答案;如果您觉得它对其他人有价值,您可以自行回答问题。

标签: ruby-on-rails rspec rspec-rails


【解决方案1】:

发现问题是我在模型验证中遇到了这个问题。我的帖子表上没有帖子属性

  validates :title, :post, presence: true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    相关资源
    最近更新 更多