我收到 NoMethodError:当我对其中一个方法运行 RSpec 测试时未定义的方法"用户"



我是编程新手,已经学习Ruby on Rails大约10周了。

当我在以下模型上运行 rspec 测试时,我不断得到

NoMethodError:
   undefined method `user' for #<Item:0xab6623c>

这是模型:

class Item < ActiveRecord::Base
  belongs_to :list
  default_scope { where("items.created_at > 7.days.ago") }
  validates :body, length: { minimum: 5 }, presence: true
  validates :user, presence: true
 end

现在,我知道该模型为用户验证,但是我已经使用Factory Girl创建了一个用户,并将其包含在我的规范中。这是我的工厂:

FactoryGirl.define do 
  factory :item do 
    body 'item body'
    list 
    user
   end
 end

用户工厂:

FactoryGirl.define do
  factory :user do
    name "John Fahey"
    sequence(:email, 100) { |n| "person#{n}@example.com" }
    password "helloworld"
    password_confirmation "helloworld"
    confirmed_at Time.now
  end
end

。这是我的规格:

require 'rails_helper'
describe Item do 
  describe "validations" do
    describe "length validation" do
      before do
        user = create(:user)
        item = create(:item, user: user)
      end
      it "only allows items with 5 or more characters." do
        i = item.body(length: 4)
        expect(i.valid?).to eq(false)
        i = item.body(length: 6)
        expect(i.valid?).to eq(true)
    end
   end
  end
 end 

我阅读了工厂女孩"入门"指南,以确保在创建用户和项目时我的语法正常,但我不确定为什么测试无法识别用户。我在这里说什么?

看起来您需要向模型添加关联,以便 Item 上存在像 user 这样的 getter 方法。

因此,您可能希望将has_one :user添加到Item,并且(根据您的需要)has_many :items User

希望有帮助。

相关内容

最新更新