ruby-on-rails – 测试Rspec时的FactoryGirl和belongs_to协会

ruby-on-rails – 测试Rspec时的FactoryGirl和belongs_to协会,第1张

概述我有以下型号: class Team < ActiveRecord::Base # Setup accessible (or protected) attributes for your model attr_accessible :name validates_presence_of :name belongs_to :userend 哪个经过测试: describe Te 我有以下型号:

class Team < ActiveRecord::Base  # Setup accessible (or protected) attributes for your model  attr_accessible :name  valIDates_presence_of :name  belongs_to :userend

哪个经过测试:

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)  endend

我有以下工厂:

FactoryGirl.define do  factory :team do    name 'Dream Team'    sport    user  endendFactoryGirl.define do  factory :user do    name 'Test User'    last_name 'Last name'    email '[email protected]'    password 'changeme'    password_confirmation 'changeme'  endend

当我测试规范时,我得到以下失败:

1) Team should belong to a user
Failure/Error: @team = Team.create!(@attr)
ActiveRecord::StatementInvalID:
sqlite3::ConstraintException: teams.user_ID may not be NulL: INSERT INTO “teams” (“created_at”,“name”,“sport_ID”,“updated_at”,
“user_ID”) VALUES (?,?,?)

这是为什么?在文档中,它表示要设置关联,您只需编写工厂名称,在我的情况下是用户.

谢谢

解决方法 FactoryGirl.attributes_for将为您提供仅包含指定模型的属性的哈希值,不包括关联属性 – 在您的情况下为user_ID.

如果user_ID是必填字段,并且您尝试使用FactoryGirl.create(attributes_for(:team))创建Team实例,则会抛出错误.

但是,如果您使用FactoryGirl.create(:team),它应该为您提供有效的Team实例.

总结

以上是内存溢出为你收集整理的ruby-on-rails – 测试Rspec时的FactoryGirl和belongs_to协会全部内容,希望文章能够帮你解决ruby-on-rails – 测试Rspec时的FactoryGirl和belongs_to协会所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1279990.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存