Skip to content

Instantly share code, notes, and snippets.

@lcjury
Created September 14, 2018 17:33
Show Gist options
  • Save lcjury/e13f706f33010d3cb80c58e87fbe5706 to your computer and use it in GitHub Desktop.
Save lcjury/e13f706f33010d3cb80c58e87fbe5706 to your computer and use it in GitHub Desktop.
cancan with STI
begin
require 'bundler/inline'
rescue LoadError => e
$stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler'
raise e
end
gemfile(true) do
source 'https://rubygems.org'
gem 'rails', '5.0.7' # use correct rails version
gem 'cancancan' # use correct cancancan version
gem 'sqlite3' # use another DB if necessary
gem 'byebug'
end
require 'active_record'
require 'cancancan'
require 'cancan/model_adapters/active_record_adapter'
require 'cancan/model_adapters/active_record_4_adapter'
require 'minitest/autorun'
require 'logger'
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
# create your tables here
ActiveRecord::Schema.define do
create_table :users, force: true do |t|
t.string :name
end
create_table :surveys, force: true do |t|
t.integer :user_id
t.string :type
end
end
class User < ActiveRecord::Base
end
class Survey < ActiveRecord::Base
end
class Climate < Survey
end
class Evaluation < Survey
end
class Ability
include CanCan::Ability
def initialize(user)
can :index, Survey
can :destroy, Evaluation
end
end
class BugTest < Minitest::Test
def test_can_index_climate_and_evaluation
Climate.create!
Evaluation.create!
ability = Ability.new(User.new)
climate = Climate.first
evaluation = Evaluation.first
assert ability.can? :index, climate
assert ability.can? :index, evaluation
end
def test_can_access_destroyable_surveys
Climate.create!
Evaluation.create!
ability = Ability.new(User.new)
evaluations = Evaluation.accessible_by(ability, :destroy)
surveys = Survey.accessible_by(ability, :destroy)
assert_equal 1, evaluations.length
assert_equal 1, surveys.length
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment