私は次のテストに合格しない理由は、私が理解することはできません。私は間違っCanCan :: AccessDenied with factory_girl and cancan、どのように工場に正しく書き込むには?私は三日目のために苦しんでいます
4) Error:
ArticlesControllerTest#test_should_get_index_if_admin:
CanCan::AccessDenied: You are not authorized to access this page.
test/controllers/articles_controller_test.rb:22:in `block in <class:ArticlesControllerTest>'
何をしているのですか?お願い助けて!
私は古いアプリケーション(レール4.2)を持っており、多くの設備データがあります。
テスト環境をフィクスチャからfactory_girlに移行しようとしました。だから私はこれが初めてだ。
今、私が使用している:
- cancancanを+
- factory_girl +のTestCase
私の記事コントローラ工夫:
class ArticlesController < ApplicationController
load_and_authorize_resource
before_filter :authenticate_user!, except: [:show]
def index
@articles = Article.paginate(page: params[:page], per_page: 10).includes(:translations)
end
end
Ability.rb:
を0私の工場のarticle.rbは非常に簡単です:
FactoryGirl.define do
factory :article do
content "MyText"
factory :one_article
factory :two_article
end
end
私の工場のuser.rbがあまりにも簡単です:
FactoryGirl.define do
factory :user do
sequence(:email) { |n| "user#{n}@mail.ru" }
password "password"
password_confirmation "password"
after(:create) {|u| u.roles_mask = 4}
profile
factory :valid_admin do
first_name "Administrator"
last_name "Administrator"
association :profile, factory: :admin_profile
after(:create) {|u| u.roles_mask = 2}
end
end
end
私の記事・コントローラー・テスト:
require 'test_helper'
class ArticlesControllerTest < ActionController::TestCase
include Devise::Test::ControllerHelpers
setup do
@article = create(:one_article)
@admin = create(:valid_admin)
end
test 'should get index if admin' do
sign_in @admin
ability = Ability.new(@admin)
assert ability.can? :index, Article
get :index
assert_response :success
assert_not_nil assigns(:articles)
end
end
情報によって、 pry:
[1] pry(#<ArticlesControllerTest>)> sign_in @admin
=> [[20709], "9BET5RWNuJPrGHUFi86d"]
[2] pry(#<ArticlesControllerTest>)> ability = Ability.new(@admin)
=> #<Ability:0x0000000c3c5ff8
@rules=
[#<CanCan::Rule:0x0000000c3c5f80
@actions=[:show],
@base_behavior=true,
@block=nil,
.............<<Many lines>> ..............
[3] pry(#<ArticlesControllerTest>)> assert ability.can? :index, Article
=> true
[4] pry(#<ArticlesControllerTest>)> get :index
CanCan::AccessDenied: You are not authorized to access this page.
from /home/da/.rvm/gems/[email protected]/gems/cancancan-1.16.0/lib/cancan/ability.rb:217:in `authorize!'
ご協力いただきありがとうございます!
::代わりにコントローラーのテストのIntegrationTest':ここ
はあなたの工場内で準備するための基礎です。また、別のテストを使用して、あなたの能力クラスをここではなく独立してテストします。 – max
私はまた、あなたが工場でやろうとしていることを実際には得られません。私は通常ffakerでFactoryGirlを使ってランダムなデータを生成します。 'factory:one_article'のようなファクトリを定義すると、フィクスチャのような匂いがします。工場は備品ではありません。ユニークなアイテムを作成する工場です。あなたの仕様にあなたの工場の値をハードコーディングしているなら、それは間違っています。いいえ: 'expect(page).to have_link(article.name)' – max
私は本当にカップの助けを借りてテストの原則を理解していませんでした。私はこの問題でより高度になった)あなたの先端のおかげでありがとう!私は余分なゴミを取り除き、いくつかのエンティティを形質で作り直しました。そして、これらのエラーは消えました! – nilid