0

我的user.rb模型中有一个回调,例如:

class User
  include Mongoid::Document
  include Mongoid::Timestamps::Created
   .
   .
   .
   .
    #add a first board for user
    after_create :first_board
      def first_board
        board = self.boards.new(:title => self.username, :category_id => Category.find_or_create_by(slug: "other"))
        board.save!
      end
end

创建用户时,应用程序会使用上述回调创建一个新版块。

在我的spec/factories/users.rb我有:

FactoryGirl.define do
  factory :user do
    name 'Test User'
    username 'test username'
    password 'please'
    password_confirmation 'please'
    # required if the Devise Confirmable module is used
    confirmed_at Time.now
  end
end

在我的spec/controllers/users_controller_spec.rb我有:

require 'spec_helper'

describe UsersController do
  before :each do
    request.env['devise.mapping'] = Devise.mappings[:user]
  end
  include Devise::TestHelpers
  before (:each) do
    @user = FactoryGirl.create(:user)
    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.slug
      assigns(:user).should == @user
    end

  end

end

如何使用 factorygirl 运行回调?

我收到 2 个错误:

Failures:

  1) UsersController GET 'show' should be successful
     Failure/Error: @user = FactoryGirl.create(:user)
     Errno::ECONNREFUSED:
       Connection refused - connect(2)
     # (eval):2:in `post'
     # ./app/models/user.rb:190:in `first_board'
     # ./spec/controllers/users_controller_spec.rb:10:in `block (2 levels) in <top (required)>'

  2) UsersController GET 'show' should find the right user
     Failure/Error: @user = FactoryGirl.create(:user)
     Errno::ECONNREFUSED:
       Connection refused - connect(2)
     # (eval):2:in `post'
     # ./app/models/user.rb:190:in `first_board'
     # ./spec/controllers/users_controller_spec.rb:10:in `block (2 levels) in <top (required)>'
4

1 回答 1

0

不能那样调用 find_or_create_by 方法,afaik。它使用 method_missing 并期望在最后添加一个 activerecord 属性。尝试:

Category.find_or_create_by_slug("other")

于 2012-07-16T20:18:44.597 回答