0

我正在尝试测试我的应用程序的 CanCan :create 规则。这是我的代码:

能力.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)

    # Admin user
    if user.is_admin?
      can :manage, :all
    end

    # Anyone
    can :read, :all

    # Regular logged in user
    if user.persisted?
      can :create, Comment
      can :create, Node
    end
  end
end

user_controller_spec.rb

require 'spec_helper'
require "cancan/matchers"

describe User do
  let(:user) { FactoryGirl.build(:user) }

  it "has a valid factory" do
    expect(user).to be_valid
  end

  # ...

  describe "abilities" do
    subject(:ability) { Ability.new(user) }
    let(:user) { nil }

    # ...

    context "when is a regular user" do
      let(:user){ FactoryGirl.build(:user) }

      it "is able to create a new node" do
        should be_able_to(:create, Node.new)
      end

      it "is not able to edit existing node" do
        @node = FactoryGirl.build(:node)
        should_not be_able_to(:update, @node) 
      end
    end
  end
end

基本上,当我实用地测试我的应用程序时,上面的代码可以正常工作,但是当我尝试运行测试时,它给了我:

Failures:

  1) User abilities when is a regular user is able to create a new node
     Failure/Error: should be_able_to(:create, Node.new)
       expected to be able to :create #<Node id: nil, title: nil, body: nil, user_id: nil, thumbnail: nil, created_at: nil, updated_at: nil, url: nil, site_id: nil, score: 0, shares_facebook: 0, shares_twitter: 0, status: nil>

我如何测试这个:创建方法?提前感谢您的帮助。

4

1 回答 1

1

我认为这里的问题是user您的规范中的 没有保留。FactoryGirl.build返回一个新对象但不将其保存到数据库中。所以user.persisted?在你的Ability.

简单的解决方法是使用FactoryGirl.create确实保留用户的方法,尽管它会使您的测试慢一点。

于 2013-10-05T10:02:00.917 回答