Skip to content

Instantly share code, notes, and snippets.

@coorasse
Last active September 13, 2024 15:27
Show Gist options
  • Save coorasse/3f00f536563249125a37e15a1652648c to your computer and use it in GitHub Desktop.
Save coorasse/3f00f536563249125a37e15a1652648c to your computer and use it in GitHub Desktop.
CanCanCan Issue
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.1.0' # use correct rails version
gem 'cancancan' # use correct cancancan version
gem 'sqlite3' # use another DB if necessary
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 :books, force: true do |t|
t.integer :user_id
end
create_table :users, force: true do |t|
t.string :name
end
end
class Book < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :books
end
class Ability
include CanCan::Ability
def initialize(user)
can :read, Book, user: user
end
end
class BugTest < Minitest::Test
def test_bug
user1 = User.create!
user2 = User.create!
books = Book.create([{user: user1},{user: user2}])
ability = Ability.new(user1)
books = Book.accessible_by(ability, :read).count
assert_equal 1, books
end
end
# class TestApp < Rails::Application
# config.root = File.dirname(__FILE__)
# config.session_store :cookie_store, key: "cookie_store_key"
# secrets.secret_token = "secret_token"
# secrets.secret_key_base = "secret_key_base"
# config.logger = Logger.new($stdout)
# Rails.logger = config.logger
# routes.draw do
# resources :libraries do
# resources :books
# end
# end
# end
# class ExampleController < ActionController::Base
# include CanCan::ControllerAdditions
# end
# class ExampleControllerTest < ActionController::TestCase
# setup do
# @controller = ExampleController.new
# @routes = Rails.application.routes
# end
# def test_action
# # ...
# end
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment