Tôi đang bắt đầu một dự án và tôi muốn có thể kiểm tra mọi thứ :)Rspec, CanCan và Devise
Và tôi có một số vấn đề với CanCan và đưa ra.
Ví dụ, tôi có bộ điều khiển Danh bạ. Mọi người đều có thể xem và tất cả mọi người (trừ những người bị cấm) có thể tạo liên lạc.
#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
Công việc mã, nhưng tôi không biết cách kiểm tra bộ điều khiển. Tôi đã thử điều này. Điều này làm việc nếu tôi nhận xét dòng 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
Nhưng những thử nghiệm này hoàn toàn thất bại .... tôi thấy không có gì trên web ... :( Vì vậy, nếu bạn có thể tư vấn cho tôi trên con đường tôi phải làm theo, tôi sẽ rất vui mừng khi tai bạn :)
Cảm ơn ryan! Tôi sẽ kiểm tra điều đó! – Arkan
Hi Ryan, tôi đã có một cái nhìn về liên kết của bạn và nhờ voxik, tôi áp dụng miếng vá của mình và bây giờ tôi có thể vượt qua tất cả các bài kiểm tra của tôi. Tôi hy vọng bạn sẽ sớm phát hành bản vá trên một phiên bản mới của Cancan. Cảm ơn một lần nữa! – Arkan