我开始一个项目,我想能检验一切:)

和我有一些问题惭惭和色器件。

有关为例,我有一个控制器联系人。每个人都可以查看和每个人(节选禁止个人)可以创建联系人。

#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

但这些测试完全没.... 我看到网络上什么... :( 所以,如果你能在我需要遵循的方式告诉我,我将很高兴为您的耳朵:)

有帮助吗?

解决方案

惭惭不调用Contact.new(params[:contact])。相反,它contact.attributes = params[:contact]以后称之为已经基于当前能力权限施加一些初始属性之后。

请参阅问题# 176关于此的细节和替代解决方案。我计划,让这个固定在惭惭版本1.5如果不是更早。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top