NameError:Rspec中的单位化常量



所以,我正在运行Rspec,并试图弄清楚为什么会出现这个错误:

Failure/Error: 3.times {@post.votes.create(value: 1) }
 NameError:
   uninitialized constant Vote::PostId

这是我的spec/models/postrongpec.rb文件:

require 'rails_helper'
describe Post do
describe "vote methods" do
before do
  @post = Post.create(title: 'post title', body: 'Post bodies must be pretty long.')
  3.times {@post.votes.create(value: 1) }
  2.times {@post.votes.create(value: -1) }
end
describe '#up_votes' do
  it "counts the number of votes with value = 1" do
    expect( @post.up_votes ).to eq(3)
  end
end
describe '#down_votes' do
  it "counts the number of votes with value = -1" do
    expect( @post.down_votes ).to eq(2)
  end
end
describe '#points' do
  it "returns the sum of all down and up votes" do
    expect( @post.points ).to eq(1) # 3 - 2
  end
end
end
end

我不明白它为什么给出这行作为错误,因为它为Rspec创建了要执行的数据。当试图在我的任何文件中查找"Vote::PostId"时,都找不到。

尝试使用@post.vots.build(值:1)

Create用于类。所以它可以是Post.create或Vote.create.

在您的情况下,它将尝试搜索Vote::PostId,这样的类不存在。

您能在Vote类中找到PostId吗?也许您试图指定一个外键,并键入了PostId而不是"PostId"

最新更新