为User和Roles定义工厂

时间:2013-09-15 12:59:42

标签: ruby-on-rails factory-bot rspec-rails

我有usersroles的应用,并且该关系有一个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'

1 个答案:

答案 0 :(得分:2)

问题是,在调用User.default_role时,尚未创建新的Role

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

  before (:each) do
    role = FactoryGirl.create(:role)
    @user = FactoryGirl.create(:user)
    @user.roles << role
    sign_in @user
  end