我对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