Farm
모델에 대한 사용자 인증을 테스트하기 위해 노력하고
다른 응답을 반환 사용자 일명 익명도 있음).캉캉 accessibly_by는 게스트로 (<strong>은 로그인 한되는 모든 농장</strong> 읽기 액세스 권한이있는 <code>:user</code> 역할이 경우, 스펙 및 컨트롤러
# /models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
# Create guest user aka. anonymous (not logged in) when user is nil.
user ||= User.new
if user.has_role? :admin
can :manage, :all
else # guest user aka. anonymous
can :read, :all
# logged in user
if user.has_role? :user
can :create, Farm
can :manage, Farm, :user_id => user.id
end
end
end
end
...
# /controllers/api/v1/farms_controller.rb
class Api::V1::FarmsController < ActionController::Base
load_and_authorize_resource
rescue_from CanCan::AccessDenied do |exception|
redirect_to farms_path, alert: exception.message
end
respond_to :json
def index
# Next line might be redundant refering to the CanCan wiki. See below..
@farms = Farm.accessible_by(current_ability, :read)
respond_with(@farms)
end
end
...
# /spec/api/v1/farm_spec.rb
require "spec_helper"
describe "/api/v1/farms" do
let(:user) { create(:user) } # lets call this user1 in the discussion
let(:token) { user.authentication_token }
before do
user.add_role :user
create(:farm, user: user, name: "Testfarm")
create(:farm, name: "Access denied")
@ability = Ability.new(user)
end
context "farms viewable by this logged-in user" do
let(:url) { "/api/v1/farms" }
it "json" do
get "#{url}.json"
farms_json = Farm.accessible_by(@ability, :read).to_json
assert last_response.ok?
last_response.body.should eql(farms_json)
last_response.status.should eql(200)
farms = JSON.parse(last_response.body)
farms.any? do |farm|
farm["name"] == "Testfarm"
end.should be_true
farms.any? do |farm|
farm["name"] == "Access denied"
end.should be_true
end
end
end
문제
내가 farms_json
을 검사
Testfarm
만이 포함되어 볼 수 있습니다. 내가
last_response
을 검사 할 때, 그것이
Testfarm
과
Access denied
을 포함하고있는 것을 볼 수있다. 동일한
accessible_by
메서드를 사용하여 동작과
index
동작을 모두 사용하기 때문에 이상합니다. 내가 사용하는 설정은
Fetching Records이라는 CanCan 보석의 위키에 설명되어 있습니다.
무용 한 해결 방법
내가 같은 농장 Access denied
에 사용자 user
에게 추가
create(:farm, user: user, name: "Access denied")
... 다음 테스트가 성공합니다.
질문은 IT가 (게스트 사용자를 포함하여) 모든 사용자가 읽을 수 있지만하지 반환 농장 "액세스가 거부되었습니다"왜
? get "#{url}.json"
은 실제로 사용자의 상태를 고려합니까? 이 모든 작업이 의 load_and_authorize_resource
으로 완료 되었습니까?@farms = Farm.accessible_by(current_ability, :read)
은 "이것은 색인 작업을 위해 load_resource
에 의해 자동으로 수행됩니다"때문에 생략 할 수 있습니다. 이것은 내 상황에 적용 되는가?실험
나는 다른 사용자 "사용자 2"다른 농장 "내 작은 농장"을 만들었습니다. 나는 그들을 서로 연결했다.- 농장 "Testfarm"사용자 2에 관련된 사용자
- 농장 "내 작은 농장"에 관련된 "액세스가 거부되었습니다"
- 농장의 user1에 관련된 :이 방법은 예제의 데이터베이스는 alltogether 세 개의 농장이 포함되어 있습니다.
Farm.accessible_by(Ability.new(user1), :read)
을 실행해도 "Testfarm"만 나타납니다.