ruby-on-rails – 测试Rspec时的FactoryGirl和belongs_to协会
我有以下型号:
class Team < ActiveRecord::Base # Setup accessible (or protected) attributes for your model attr_accessible :name validates_presence_of :name belongs_to :user end 哪个经过测试: describe Team do before(:each) do @attr = FactoryGirl.attributes_for(:team) end it "should belong to a user" do @team = Team.create!(@attr) @team.should belong_to(:user) end end 我有以下工厂: FactoryGirl.define do factory :team do name 'Dream Team' sport user end end FactoryGirl.define do factory :user do name 'Test User' last_name 'Last Name' email 'example@example.com' password 'changeme' password_confirmation 'changeme' end end 当我测试规范时,我得到以下失败:
这是为什么?在文档中,它表示要设置关联,您只需编写工厂名称,在我的情况下是用户. 谢谢 解决方法
FactoryGirl.attributes_for将为您提供仅包含指定模型的属性的哈希值,不包括关联属性 – 在您的情况下为user_id.
如果user_id是必填字段,并且您尝试使用FactoryGirl.create(attributes_for(:team))创建Team实例,则会抛出错误. 但是,如果您使用FactoryGirl.create(:team),它应该为您提供有效的Team实例. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |