[英]I'm getting NoMethodError: undefined method `user' when I run an RSpec test on one of my methods
我是編程新手,並且已經學習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
我閱讀了工廠女孩“入門”指南,以確保在創建用戶和商品時我的語法正確,但是我不確定測試為什么能識別用戶。 我在這里發短信嗎?
看起來您需要向模型中添加關聯,以使諸如user
類的getter方法存在於Item上。
因此,您可能想將has_one :user
添加到Item
,並將(取決於您的需要) has_many :items
到User
。
希望能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.