我最近将应用程序升级到rails 3.2.2。
我正在使用Factory_girl
Factory.sequence:name do | n | “name - #{n}”end
Factory.define:用户执行| u | u.first_name {Factory.next(:name)}
u.last_name {| u | 'last_'+ u.first_name} u.password'secret'
u.password_confirmation {| u | u.password} u.sequence(:email){| i | “user_#{i}@example.com”}端
和这个简单的测试
指定{Factory.build(:user).should be_valid}
生成以下警告
DEPRECATION警告:您正在尝试创建属性
user_id'. Writing arbitrary attributes on a model is deprecated. Please just use
attr_writer`等(从块(2级)调用 在...
我该怎样摆脱它?
答案 0 :(得分:19)
这可能是因为您没有使用更新的列定义准备/迁移测试数据库,因此它认为您正在尝试任意设置属性。
运行rake db:test:prepare
以确保其已更新。
Here's the source code,您可以先看到Rails检查列或属性,然后警告它们是否找不到。
答案 1 :(得分:4)
我用以下代码遇到了同样的警告:
广告模式:
class Ad < ActiveRecord::Base
belongs_to :user
end
工厂:
FactoryGirl.define do
factory :ad do
association :user
end
end
FactoryGirl.define do
factory :user do
first_name {Factory.next(:first_name)}
last_name {Factory.next(:last_name)}
email {|x| "#{x.first_name}.#{x.last_name}#{Factory.next(:count)}@test.com"}
password Forgery(:basic).password
confirmed_at Date.today << 10
end
end
测试
require 'spec_helper'
describe Ad do
before(:each) do
@ad = Factory.build(:ad)
end
"it is not valid without a user"
end
运行测试给我一个类似的错误。
添加
attr_accessor :user
广告模型修复了警告。
我希望它有所帮助。
答案 2 :(得分:0)
我在Rspec进行测试时遇到了同样的警告,我的问题是我有一个父模型和儿童模型我不小心有这个:
class Child < ActiveRecord::Base
belongs_to :parent
end
......
class Parent < ActiveRecord::Base
belongs_to :child
end