在factorygirl上运行回调

时间:2012-07-16 11:22:41

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

我的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)>'

1 个答案:

答案 0 :(得分:0)

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

Category.find_or_create_by_slug("other")