Skip to content

Instantly share code, notes, and snippets.

@samwgoldman
Created May 24, 2013 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samwgoldman/5643793 to your computer and use it in GitHub Desktop.
Save samwgoldman/5643793 to your computer and use it in GitHub Desktop.
require "active_record"
require "rspec/autorun"
class Migrate < ActiveRecord::Migration
self.verbose = false
def up
create_table(:projects)
create_table(:tasks) do |t|
t.references :project, null: false
t.text :external_id
end
end
end
class Project < ActiveRecord::Base
has_many :tasks
end
class Task < ActiveRecord::Base
ExternalIDAlreadyInUse = Class.new(Exception)
belongs_to :project
def self.import_implicit_self(external_id)
if exists?(external_id: external_id)
raise ExternalIDAlreadyInUse
else
create(external_id: external_id)
end
end
def self.import_explicit_class(external_id)
if Task.exists?(external_id: external_id)
raise ExternalIDAlreadyInUse
else
create(external_id: external_id)
end
end
def self.import_unscoped(external_id)
if unscoped.exists?(external_id: external_id)
raise ExternalIDAlreadyInUse
else
create(external_id: external_id)
end
end
end
describe "ActiveRecord relation scope" do
before do
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
Migrate.new.up
end
it "has an implicit scope when used with implicit self" do
one = Project.create
two = Project.create
one.tasks.import_implicit_self(1)
two.tasks.import_implicit_self(1)
end
it "has an implicit scope when used with explicit class" do
one = Project.create
two = Project.create
one.tasks.import_explicit_class(1)
two.tasks.import_explicit_class(1)
end
it "can be unscoped" do
one = Project.create
two = Project.create
one.tasks.import_unscoped(1)
expect {
two.tasks.import_unscoped(1)
}.to raise_error(Task::ExternalIDAlreadyInUse)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment