0

我有一个带有usersand的应用程序roles,带有一个users_roles关系表。我正在尝试为UserRole模型定义工厂:

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'
4

1 回答 1

2

问题是,当User.default_role被调用时,新的Role还没有被创建。

只需将测试更改为以下内容:

  before (:each) do
    role = FactoryGirl.create(:role)
    @user = FactoryGirl.create(:user)
    @user.roles << role
    sign_in @user
  end
于 2013-09-15T13:22:20.393 回答