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>

この :create メソッドをテストするにはどうすればよいですか? 助けてくれてありがとう。

4

1 に答える 1

1

userここでの問題は、仕様の が永続化されていないことだと思います。FactoryGirl.build新しいオブジェクトを返しますが、データベースには保存しません。したがってuser.persisted?、あなたのAbility.

簡単な修正はFactoryGirl.create、ユーザーを永続化するものを使用することですが、テストが少し遅くなります。

于 2013-10-05T10:02:00.917 に答える