【发布时间】:2013-03-21 07:57:26
【问题描述】:
我有以下型号:
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
当我测试规范时,我得到以下失败:
1) 团队应该属于一个用户 失败/错误:@team = Team.create!(@attr) ActiveRecord::StatementInvalid: SQLite3::ConstraintException:teams.user_id 可能不是 NULL:INSERT INTO "teams" ("created_at", "name", "sport_id", "updated_at", "user_id") 值 (?, ?, ?, ?, ?)
这是为什么呢?在文档中它说要设置关联,您只需编写工厂名称,在我的例子中是用户。
谢谢
【问题讨论】:
-
我认为您使用的是
shoulda-matchers或remarkable? -
直 rspec-rails 2.13.0
-
除非我大错特错,否则我不认为
belong_to是 RSpec 2 中的默认匹配器之一。您需要其他东西才能编写它。 relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
标签: ruby-on-rails rspec factory-bot