我是编程新手,现在已经学习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
我读了工厂女孩&#34;开始&#34;在创建用户和项目时确保我的语法正常的指南,但我不确定为什么测试不是&#39;识别用户。我在这里忙什么?
答案 0 :(得分:1)
看起来你需要为你的模型添加关联,以便在Item上存在像user
这样的getter方法。
因此,您可能希望将has_one :user
添加到Item
,并(根据您的需要)has_many :items
添加到User
。
希望有所帮助。