5
我開始一個項目,我希望能夠測試所有內容:)Rspec,CanCan和Devise
我還有一些CanCan和設計問題。
例如,我有一個控制器通訊錄。每個人都可以查看,每個人(除禁止人)都可以建立聯繫。
#app/controllers/contacts_controller.rb
class ContactsController < ApplicationController
load_and_authorize_resource
def index
@contact = Contact.new
end
def create
@contact = Contact.new(params[:contact])
if @contact.save
respond_to do |f|
f.html { redirect_to root_path, :notice => 'Thanks'}
end
else
respond_to do |f|
f.html { render :action => :index }
end
end
end
end
代碼工作,但我不怎麼測試控制器。 我試過了。如果我評論load_and_authorize_resource行,這將起作用。
#spec/controllers/contacts_controller_spec.rb
require 'spec_helper'
describe ContactsController do
def mock_contact(stubs={})
(@mock_ak_config ||= mock_model(Contact).as_null_object).tap do |contact|
contact.stub(stubs) unless stubs.empty?
end
end
before (:each) do
# @user = Factory.create(:user)
# sign_in @user
# @ability = Ability.new(@user)
@ability = Object.new
@ability.extend(CanCan::Ability)
@controller.stubs(:current_ability).returns(@ability)
end
describe "GET index" do
it "assigns a new contact as @contact" do
@ability.can :read, Contact
Contact.stub(:new) { mock_contact }
get :index
assigns(:contact).should be(mock_contact)
end
end
describe "POST create" do
describe "with valid params" do
it "assigns a newly created contact as @contact" do
@ability.can :create, Contact
Contact.stub(:new).with({'these' => 'params'}) { mock_contact(:save => true) }
post :create, :contact => {'these' => 'params'}
assigns(:contact).should be(mock_contact)
end
it "redirects to the index of contacts" do
@ability.can :create, Contact
Contact.stub(:new) { mock_contact(:save => true) }
post :create, :contact => {}
response.should redirect_to(root_url)
end
end
describe "with invalid params" do
it "assigns a newly created but unsaved contact as @contact" do
@ability.can :create, Contact
Contact.stub(:new).with({'these' => 'params'}) { mock_contact(:save => false) }
post :create, :contact => {'these' => 'params'}
assigns(:contact).should be(mock_contact)
end
it "re-renders the 'new' template" do
@ability.can :create, Contact
Contact.stub(:new) { mock_contact(:save => false) }
post :create, :contact => {}
response.should render_template("index")
end
end
end
end
但這些測試完全沒.... 我什麼也沒看到在網絡上... :( 所以,如果你能在我需要遵循的方式告訴我,我會很高興的耳朵你:)
謝謝瑞安!我會檢查一下! – Arkan 2010-11-17 18:11:15
嗨瑞安,我看了一下你的鏈接,感謝voxik,我申請了他的補丁,現在我能夠通過我的所有測試。我希望你很快就能在新版本的Cancan上發佈這個補丁。再次感謝 ! – Arkan 2010-11-17 23:16:59