我對Rspec很陌生,正在將代碼庫從Rails 3.0.x遷移到Rails 3.1.x並同時添加測試。我能夠獲得基本的控制器測試工作,但在開始整合Devise後,我開始遇到問題。具體來說,我有一個名爲User
的Devise對象,屬於Company
,而Company
有很多Communities
。我試圖爲Communities
控制器編寫測試,當嘗試通過關聯引用(例如controller.current_user.communities
)時,我無法引用我創建的Factory對象。當我嘗試測試,我得到以下(或類似)錯誤:Rspec + Devise +關聯工廠女孩測試
No route matches {:id=>nil, :controller=>"communities", :action=>"edit"}
我敢肯定,我失去了一些東西基本涉及到Rspec的/ Factory_Girl,但任何幫助,將不勝感激。
設置用於測試edit
行動Communities
的一個例子是如下:
/config/routes.rb
Units::Application.routes.draw do
devise_for :users
resources :companies
resources :communities
...
root :to => 'companies#index'
end
/app/models/user.rb
class User < ActiveRecord::Base
belongs_to :company
has_many :communities, :through => :company
...
end
/app/models/company.rb
class Company < ActiveRecord::Base
has_many :users
has_many :communities
...
end
/app/models/community.rb
class Community < ActiveRecord::Base
belongs_to :company
...
end
/spec/controllers/communities_controller_spec.rb
require 'spec_helper'
describe CommunitiesController do
render_views
login_user
...
context "GET #edit" do
before(:each) do
@company = controller.current_user.company
@community = controller.current_user.communities.new[Factory.build(:community, :company => @company)]
controller.current_user.company.communities.should_receive(:find).with(:company => @company)
end
it "should be successful" do
get :edit, :id => @community
response.should be_successful
end
it "should find a specific community" do
get :edit, :id => @community
assigns(:community).should eq(@community)
end
end
...
end
/app/controllers/communities_controller.rb
class CommunitiesController < ApplicationController
...
def edit
@community = current_user.communities.find(params[:id])
end
...
end
/spec/support/controller_macros.rb
module ControllerMacros
def login_user
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
company = Factory.create(:company)
user = Factory.create(:user, :company => company)
# user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the confirmable module
sign_in user
end
end
end
請添加你的'config/routes.rb' – lucapette 2012-02-23 16:48:32
你可以在'it'中添加'p @ community'應該是成功的''部分並給我們結果? – farnoy 2012-02-24 21:30:37
@farnoy我在該部分放了'p @ community',但它沒有改變輸出。我仍然收到以下錯誤: '失敗/錯誤:get:edit,:id => @community ActionController :: RoutingError: 沒有路由匹配{:id => nil,:controller =>「communities」 ,:action =>「edit」}' – theandym 2012-02-26 03:03:11