我有一个带有users
and的应用程序roles
,带有一个users_roles
关系表。我正在尝试为User
和Role
模型定义工厂:
FactoryGirl.define do
factory :user do
name 'Test User'
email 'example@example.com'
password 'changeme'
password_confirmation 'changeme'
# required if the Devise Confirmable module is used
# confirmed_at Time.now
end
factory :role do
name 'user'
end
end
和我的测试
require 'spec_helper'
describe UsersController do
before (:each) do
@user = FactoryGirl.create(:user)
@user.role = FactoryGirl.create(:role)
sign_in @user
end
describe "GET 'show'" do
it "should be successful" do
get :show, :id => @user.id
response.should be_success
end
it "should find the right user" do
get :show, :id => @user.id
assigns(:user).should == @user
end
end
end
模型
private
def default_role
self.roles << Role.where(:name => 'user').first
end
当我运行 rspec 时,我遇到了一个错误
Failure/Error: User.create!(@attr)
ActiveRecord::AssociationTypeMismatch:
Role(#68298640) expected, got NilClass(#14882680)
# ./app/models/user.rb:33:in `default_role'