RuboCop: Rails/FilePath

[skip-stages=Flakey]

manual

also use methods on Pathname while we're auditing these, to simplify

Change-Id: I4ff00329a7de9d39f5797790c22b55f7bb661c05
Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/278481
Tested-by: Service Cloud Jenkins <svc.cloudjenkins@instructure.com>
Reviewed-by: Jacob Burroughs <jburroughs@instructure.com>
QA-Review: Cody Cutrer <cody@instructure.com>
Product-Review: Cody Cutrer <cody@instructure.com>
This commit is contained in:
Cody Cutrer 2021-11-16 15:22:01 -07:00
parent fc57b56746
commit a4c592de50
54 changed files with 114 additions and 111 deletions

View File

@ -120,6 +120,8 @@ Rails/DynamicFindBy:
- find_by_pseudonym_credentials # SessionPersistenceToken
- find_by_quiz # Quizzes::OutstandingQuizSubmissionManager
Severity: error
Rails/FilePath:
Severity: error
Rails/HasManyOrHasOneDependent:
Enabled: false # legacy code + most things we soft delete anyway
Rails/HelperInstanceVariable:

View File

@ -1680,7 +1680,7 @@ class ApplicationController < ActionController::Base
template = exception.error_template if exception.respond_to?(:error_template)
unless template
template = "shared/errors/#{status.to_s[0, 3]}_message"
erbpath = Rails.root.join('app', 'views', "#{template}.html.erb")
erbpath = Rails.root.join("app/views/#{template}.html.erb")
template = "shared/errors/500_message" unless erbpath.file?
end

View File

@ -1517,7 +1517,7 @@ class Attachment < ActiveRecord::Base
end
def self.file_removed_path
Rails.root.join('public', 'file_removed', 'file_removed.pdf')
Rails.root.join('public/file_removed/file_removed.pdf')
end
# find the file_removed file on instfs (or upload it)

View File

@ -31,7 +31,7 @@ class AuthenticationProvider::SAML::InCommon < AuthenticationProvider::SAML::Fed
protected
def cert
Rails.root.join("config", "saml", "inc-md-cert.pem").read
Rails.root.join("config/saml/inc-md-cert.pem").read
end
end
end

View File

@ -31,7 +31,7 @@ class AuthenticationProvider::SAML::UKFederation < AuthenticationProvider::SAML:
protected
def cert
Rails.root.join("config", "saml", "ukfederation.pem").read
Rails.root.join("config/saml/ukfederation.pem").read
end
end
end

View File

@ -40,6 +40,6 @@ class EtherpadCollaboration < Collaboration
end
def self.config
Canvas::Plugin.find(:etherpad).try(:settings) || (YAML.load_file(Rails.root + "config/etherpad.yml")[Rails.env] rescue nil)
Canvas::Plugin.find(:etherpad).try(:settings) || (YAML.load_file(Rails.root.join("config/etherpad.yml"))[Rails.env] rescue nil)
end
end

View File

@ -26,7 +26,7 @@ module Quizzes
# lazy loading for STI models ( https://guides.rubyonrails.org/autoloading_and_reloading_constants.html#single-table-inheritance ).
module Preloader
def self.preload_quiz_questions
Dir[Rails.root + "app/models/quizzes/quiz_question/*_question.rb"].each do |f|
Dir[Rails.root.join("app/models/quizzes/quiz_question/*_question.rb")].each do |f|
filename = f.split("/").last
snake_case_const = filename.split(".").first
::Quizzes.const_get("QuizQuestion::#{snake_case_const.camelize}")

View File

@ -79,4 +79,4 @@ class Quizzes::QuizQuestion::UserAnswer < Struct.new(:question_id, :points_possi
end
end
(Dir[Rails.root + "app/models/quizzes/quiz_question/*_answer.rb"] - [__FILE__]).each { |f| require_dependency f }
(Dir[Rails.root.join("app/models/quizzes/quiz_question/*_answer.rb")] - [__FILE__]).each { |f| require_dependency f }

View File

@ -102,7 +102,7 @@ module CanvasRails
# Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time.
config.time_zone = 'UTC'
log_config = File.exist?(Rails.root + 'config/logging.yml') && Rails.application.config_for(:logging).with_indifferent_access
log_config = Rails.root.join('config/logging.yml').file? && Rails.application.config_for(:logging).with_indifferent_access
log_config = { 'logger' => 'rails', 'log_level' => 'debug' }.merge(log_config || {})
opts = {}
require 'canvas_logger'
@ -128,7 +128,7 @@ module CanvasRails
log_path = config.paths['log'].first
if ENV['RUNNING_AS_DAEMON'] == 'true'
log_path = Rails.root + 'log/delayed_job.log'
log_path = Rails.root.join('log/delayed_job.log')
end
config.logger = CanvasLogger.new(log_path, log_level, opts)
@ -145,9 +145,9 @@ module CanvasRails
# prevent directory->module inference in these directories from wreaking
# havoc on the app (e.g. stylesheets/base -> ::Base)
config.eager_load_paths -= %W(#{Rails.root}/app/coffeescripts
#{Rails.root}/app/stylesheets
#{Rails.root}/ui)
config.eager_load_paths -= [Rails.root.join("app/coffeescripts"),
Rails.root.join("app/stylesheets"),
Rails.root.join("ui")]
config.middleware.use Rack::Chunked
config.middleware.use Rack::Deflater, if: ->(*) {
@ -157,8 +157,8 @@ module CanvasRails
::Canvas::DynamicSettings.find(tree: :private)["enable_rack_brotli", failsafe: true]
}
config.i18n.load_path << Rails.root.join('config', 'locales', 'locales.yml')
config.i18n.load_path << Rails.root.join('config', 'locales', 'community.csv')
config.i18n.load_path << Rails.root.join('config/locales/locales.yml')
config.i18n.load_path << Rails.root.join('config/locales/community.csv')
config.to_prepare do
require_dependency 'canvas/plugins/default_plugins'
@ -253,9 +253,6 @@ module CanvasRails
Autoextend.hook(:"Thor::Option", PatchThorWarning, method: :prepend)
# Extend any base classes, even gem classes
Dir.glob("#{Rails.root}/lib/ext/**/*.rb").sort.each { |file| require file }
# tell Rails to use the native XML parser instead of REXML
ActiveSupport::XmlMini.backend = 'Nokogiri'

View File

@ -1535,7 +1535,7 @@ module MigratorCache
end
def migrations_paths
@@migrations_paths ||= [File.join(Rails.root, "db/migrate")]
@@migrations_paths ||= [Rails.root.join("db/migrate")]
end
end
ActiveRecord::Migrator.singleton_class.prepend(MigratorCache)
@ -1577,7 +1577,7 @@ module Migrator
end
ActiveRecord::Migrator.prepend(Migrator)
ActiveRecord::Migrator.migrations_paths.concat Dir[Rails.root.join('gems', 'plugins', '*', 'db', 'migrate')]
ActiveRecord::Migrator.migrations_paths.concat Dir[Rails.root.join('gems/plugins/*/db/migrate')]
ActiveRecord::Tasks::DatabaseTasks.migrations_paths = ActiveRecord::Migrator.migrations_paths

View File

@ -17,4 +17,4 @@
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
ApiScopeMapperFallback.register_fallback unless File.exist?(Rails.root.join('lib/api_scope_mapper.rb'))
ApiScopeMapperFallback.register_fallback unless Rails.root.join('lib/api_scope_mapper.rb').file?

View File

@ -24,4 +24,4 @@
# application.rb? this is to conform to https://guides.rubyonrails.org/autoloading_and_reloading_constants.html
# which states "Please, do not mutate ActiveSupport::Dependencies.autoload_paths,
# the public interface to change autoload paths is config.autoload_paths."
ActiveSupport::Dependencies.autoload_paths.push(Rails.root + 'lib/stubs')
ActiveSupport::Dependencies.autoload_paths.push(Rails.root.join('lib/stubs'))

View File

@ -24,7 +24,7 @@ if CANVAS_ZEITWERK
# This is because the jsx folder does not contain ruby to
# autoload. You should NOT use this pattern as a workaround
# for badly-named ruby code.
Rails.autoloaders.main.ignore(Rails.root.join('app', 'jsx'))
Rails.autoloaders.main.ignore(Rails.root.join('app/jsx'))
Rails.autoloaders.main.ignore(
# we don't want zeitwerk to try to eager_load some "Version" constant from any plugins

View File

@ -24,7 +24,7 @@ class ApiScopeMappingWriter
@resources = resources
dir = File.dirname(__FILE__)
@template = File.read(File.join(dir, '/scope_mapper_template.erb'))
@output_file = Rails.root.join("lib", "api_scope_mapper.rb")
@output_file = Rails.root.join("lib/api_scope_mapper.rb")
@resource_lookup = {}
end

View File

@ -23,7 +23,7 @@ $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), 'api_scopes'))
require 'controller_list_view'
require 'api_scope_mapping_writer'
Dir.glob("#{Rails.root}/doc/api/data_services/*.rb").sort.each { |file| require file }
Dir.glob(Rails.root.join("doc/api/data_services/*.rb")).sort.each { |file| require file }
include Helpers::ModuleHelper
include Helpers::FilterHelper

View File

@ -35,7 +35,7 @@ class ControllerListView < HashView
end
def config_domain_yaml
YAML.load(File.read(File.join(Rails.root, 'config', 'domain.yml'))) if File.exist?(File.join(Rails.root, 'config', 'domain.yml'))
YAML.load(Rails.root.join('config/domain.yml').read) if Rails.root.join('config/domain.yml').file?
end
def canvas_url

View File

@ -35,7 +35,7 @@ class RouteView < HashView
def file_path
filepath = "app/controllers/#{@method_view.controller}_controller.rb"
filepath = nil unless File.file?(File.join(Rails.root, filepath))
filepath = nil unless Rails.root.join(filepath).file?
filepath
end

View File

@ -43,5 +43,5 @@ def get_routes
@routes = ApiRouteSet.api_methods_for_controller_and_action(@controller, @action)
@route = @routes.first
@controller_path = "app/controllers/#{@route.requirements[:controller]}_controller.rb"
@controller_path = nil unless File.file?(Rails.root + @controller_path)
@controller_path = nil unless Rails.root.join(@controller_path).file?
end

View File

@ -55,7 +55,7 @@ rescue ActiveRecord::PendingMigrationError => e
end
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.fixture_path = ::Rails.root.join("spec/fixtures")
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false

View File

@ -155,7 +155,7 @@ module AttachmentFu # :nodoc:
end
def self.load_s3_config(path = nil)
s3_config_path = path || (Rails.root + 'config/amazon_s3.yml')
s3_config_path = path || Rails.root.join('config/amazon_s3.yml')
YAML.load(ERB.new(File.read(s3_config_path)).result)[Rails.env].symbolize_keys
end

View File

@ -83,10 +83,10 @@ module CanvasSecurity
def self.config
@config ||= begin
path = Rails.root + 'config/security.yml'
raise('config/security.yml missing, see security.yml.example') unless File.exist?(path)
path = Rails.root.join('config/security.yml')
raise('config/security.yml missing, see security.yml.example') unless path.file?
YAML.safe_load(ERB.new(File.read(path)).result, aliases: true)[Rails.env]
YAML.safe_load(ERB.new(path.read).result, aliases: true)[Rails.env]
end
end

View File

@ -212,7 +212,7 @@ describe CanvasSecurity do
it 'loads config as erb from config/security.yml' do
config = "test:\n encryption_key: <%= ENV['ENCRYPTION_KEY'] %>"
expect(File).to receive(:read).with(Rails.root + 'config/security.yml').and_return(config)
expect(File).to receive(:read).with(Rails.root.join('config/security.yml').to_s).and_return(config)
expect(ENV).to receive(:[]).with('ENCRYPTION_KEY').and_return('secret')
expect(CanvasSecurity.config).to eq('encryption_key' => 'secret')
end

View File

@ -43,9 +43,9 @@ module ConfigFile
return @yaml_cache[config_name]&.[](with_rails_env)
end
path = Rails.root.join('config', "#{config_name}.yml")
if File.exist?(path)
config_string = ERB.new(File.read(path))
path = Rails.root.join("config/#{config_name}.yml")
if path.file?
config_string = ERB.new(path.read)
config = YAML.safe_load(config_string.result, aliases: true)
config = config.with_indifferent_access if config.respond_to?(:with_indifferent_access)
end

View File

@ -33,8 +33,10 @@ describe ConfigFile do
end
it "caches objects" do
expect(File).to receive(:exist?).and_return(true)
expect(File).to receive(:read).and_return('test: {}')
file = instance_double("Pathname")
expect(Rails.root).to receive(:join).with("config/my_config.yml").and_return(file)
expect(file).to receive(:file?).and_return(true)
expect(file).to receive(:read).and_return('test: {}')
hit_block = 0
result1 = ConfigFile.cache_object('my_config') do |config|
hit_block += 1
@ -52,8 +54,10 @@ describe ConfigFile do
end
it "caches YAML even if it has to load multiple objects" do
expect(File).to receive(:exist?).once.and_return(true)
expect(File).to receive(:read).once.and_return("test: a\nenv2: b")
file = instance_double("Pathname")
expect(Rails.root).to receive(:join).with("config/my_config.yml").and_return(file)
expect(file).to receive(:file?).and_return(true)
expect(file).to receive(:read).once.and_return("test: a\nenv2: b")
hit_block = 0
result1 = ConfigFile.cache_object('my_config') do |config|
hit_block += 1

View File

@ -68,7 +68,7 @@ namespace :i18n do
moment_locale
}.freeze
File.open(Rails.root.join(yaml_file), "w") do |file|
Rails.root.join(yaml_file).open("w") do |file|
file.write(
{
'en' => deep_sort_hash_by_keys(
@ -100,10 +100,10 @@ namespace :i18n do
require 'active_record'
require 'will_paginate'
I18n.load_path.unshift(*WillPaginate::I18n.load_path)
I18n.load_path += Dir[Rails.root.join('gems', 'plugins', '*', 'config', 'locales', '*.{rb,yml}')]
I18n.load_path += Dir[Rails.root.join('config', 'locales', '*.{rb,yml}')]
I18n.load_path += Dir[Rails.root.join('config', 'locales', 'locales.yml')]
I18n.load_path += Dir[Rails.root.join('config', 'locales', 'community.csv')]
I18n.load_path += Dir[Rails.root.join('gems/plugins/*/config/locales/*.{rb,yml}')]
I18n.load_path += Dir[Rails.root.join('config/locales/*.{rb,yml}')]
I18n.load_path += Dir[Rails.root.join('config/locales/locales.yml')]
I18n.load_path += Dir[Rails.root.join('config/locales/community.csv')]
I18n::Backend::Simple.include I18nTasks::CsvBackend
I18n::Backend::Simple.include I18n::Backend::Fallbacks
@ -544,7 +544,7 @@ namespace :i18n do
exit
end
Dir.chdir(Rails.root.join("config", "locales"))
Dir.chdir(Rails.root.join("config/locales"))
locales_data = YAML.safe_load(open("locales.yml"))
Dir.each_child(".") do |filename|

View File

@ -22,8 +22,8 @@ require 'shellwords'
module Qti
PYTHON_MIGRATION_EXECUTABLE = 'migrate.py'
EXPECTED_LOCATION = Rails.root.join('vendor', 'QTIMigrationTool', PYTHON_MIGRATION_EXECUTABLE).to_s rescue nil
EXPECTED_LOCATION_ALT = Rails.root.join('vendor', 'qti_migration_tool', PYTHON_MIGRATION_EXECUTABLE).to_s rescue nil
EXPECTED_LOCATION = Rails.root.join('vendor/QTIMigrationTool', PYTHON_MIGRATION_EXECUTABLE).to_s rescue nil
EXPECTED_LOCATION_ALT = Rails.root.join('vendor/qti_migration_tool', PYTHON_MIGRATION_EXECUTABLE).to_s rescue nil
@migration_executable = nil
if File.exist?(EXPECTED_LOCATION)

View File

@ -140,7 +140,7 @@ module BrandableCSS
def skip_migration_check?
# our canvas_rspec build doesn't even run `yarn install` or `gulp rev` so since
# they are not expecting all the frontend assets to work, this check isn't useful
Rails.env.test? && !Rails.root.join('public', 'dist', 'rev-manifest.json').exist?
Rails.env.test? && !Rails.root.join('public/dist/rev-manifest.json').exist?
end
def default_variables_md5

View File

@ -126,8 +126,8 @@ module Canvas
def self.revision
return @revision if defined?(@revision)
@revision = if File.file?(Rails.root + "VERSION")
File.readlines(Rails.root + "VERSION").first.try(:strip)
@revision = if Rails.root.join("VERSION").file?
Rails.root.join("VERSION").readlines.first.try(:strip)
else
nil
end

View File

@ -105,7 +105,7 @@ module Canvas
RequestCache.cache("rev-manifest") do
benchmark("reading rev-manifest") do
file = Rails.root.join('public', 'dist', 'rev-manifest.json')
file = Rails.root.join('public/dist/rev-manifest.json')
if file.exist?
Rails.logger.debug "reading rev-manifest.json"
@gulp_manifest = JSON.parse(file.read).freeze

View File

@ -20,7 +20,7 @@
module Canvas::MessageHelper
def self.default_message_path(filename)
File.join(Rails.root.to_s, 'app', 'messages', filename)
Rails.root.join('app/messages', filename).to_s
end
def self.add_message_path(path)

View File

@ -25,7 +25,7 @@ module CC
def self.for_version(version)
return nil unless whitelist.include?(version)
Rails.root + "#{XSD_DIRECTORY}/#{version}.xsd"
Rails.root.join("#{XSD_DIRECTORY}/#{version}.xsd")
end
def self.whitelist

View File

@ -174,7 +174,7 @@ class ContentZipper
add_attachment_to_zip(a.attachment, zipfile, a.unencoded_filename)
update_progress(zip_attachment, index, count)
end
content = File.open(Rails.root.join('public', 'images', 'logo.png'), 'rb').read rescue nil
content = Rails.root.join('public/images/logo.png').read rescue nil
zipfile.get_output_stream("logo.png") { |f| f.write content } if content
end
mark_successful!

View File

@ -250,7 +250,7 @@ class CourseLinkValidator
path = path.chomp("/")
@route_set ||= ::Rails.application.routes.set.routes.select { |r| r.verb === "GET" }
@route_set.any? { |r| r.path.match(path) } || (!Pathname(path).each_filename.include?('..') && File.exist?(File.join(Rails.root, "public", path)))
@route_set.any? { |r| r.path.match(path) } || (!Pathname(path).each_filename.include?('..') && Rails.root.join("public", path[1..]).file?)
end
# makes sure that links to course objects exist and are in a visible state

View File

@ -66,8 +66,8 @@ module FeatureFlags
def self.load_yaml_files
result = {}
(Dir.glob(Rails.root.join('config', 'feature_flags', '*.yml')) +
Dir.glob(Rails.root.join('gems', 'plugins', '*', 'config', 'feature_flags', '*.yml'))).sort.each do |path|
(Dir.glob(Rails.root.join('config/feature_flags/*.yml')) +
Dir.glob(Rails.root.join('gems/plugins/*/config/feature_flags/*.yml'))).sort.each do |path|
result.merge!(YAML.load_file(path))
end
result.each do |_name, definition|

View File

@ -24,7 +24,7 @@ end
namespace :db do
desc "Generate security.yml key"
task :generate_security_key do
security_conf_path = Rails.root.join('config', 'security.yml')
security_conf_path = Rails.root.join('config/security.yml')
security_conf = YAML.load_file(security_conf_path)
if security_conf[Rails.env]["encryption_key"].to_s.length < 20
security_conf[Rails.env]["encryption_key"] = SecureRandom.hex(64)
@ -45,7 +45,7 @@ namespace :db do
desc "Make sure all message templates have notifications in the db"
task :evaluate_notification_templates => :load_environment do
Dir.glob(Rails.root.join('app', 'messages', '*.erb')) do |filename|
Dir.glob(Rails.root.join('app/messages/*.erb')) do |filename|
filename = File.split(filename)[1]
name = filename.split(".")[0]
unless name[0, 1] == "_"

View File

@ -6,7 +6,7 @@ begin
require 'config/initializers/json'
DOC_DIR = File.join(%w[public doc api])
API_DOC_DIR = File.expand_path(Rails.root + DOC_DIR)
API_DOC_DIR = Rails.root.join(DOC_DIR).expand_path
DOC_OPTIONS = {
# turning this on will show all the appendixes of all
# controllers in the All Resources page

View File

@ -5,11 +5,11 @@ namespace :graphql do
task schema: :environment do
GraphQLPostgresTimeout.do_not_wrap = true
File.open("#{Rails.root}/schema.graphql", "w") { |f|
Rails.root.join("schema.graphql").open("w") do |f|
f.puts CanvasSchema.to_definition
}
end
File.open("#{Rails.root}/ui/shared/apollo/fragmentTypes.json", "w") { |f|
Rails.root.join("ui/shared/apollo/fragmentTypes.json").open("w") do |f|
types = CanvasSchema.execute(<<~GQL)
{
__schema {
@ -25,7 +25,7 @@ namespace :graphql do
GQL
types["data"]["__schema"]["types"].reject! { |t| t["possibleTypes"].nil? }
f.puts JSON.pretty_generate(types["data"])
}
end
end
namespace :subgraph do

View File

@ -110,21 +110,21 @@ unless Rails.env.production? || ARGV.any? { |a| a.start_with?('gems') }
[:models, :services, :controllers, :views, :helpers, :lib, :selenium].each do |sub|
desc "Run the code examples in spec/#{sub}"
klass.new(sub) do |t|
t.spec_opts = ['--options', "\"#{Rails.root}/spec/spec.opts\""]
t.spec_opts = ['--options', Shellwords.escape(Rails.root.join("spec/spec.opts"))]
t.send(spec_files_attr, FileList["spec/#{sub}/**/*_spec.rb"])
end
end
desc "Run the code examples in {gems,vendor}/plugins (except RSpec's own)"
klass.new(:coverage) do |t|
t.spec_opts = ['--options', "\"#{Rails.root}/spec/spec.opts\""]
t.spec_opts = ['--options', Shellwords.escape(Rails.root.join("spec/spec.opts"))]
t.send(spec_files_attr, FileList['{gems,vendor}/plugins/*/spec_canvas/**/*_spec.rb'].exclude(%r'spec_canvas/selenium') + FileList['spec/**/*_spec.rb'].exclude(%r'spec/selenium'))
end
namespace :plugins do
desc "Runs the examples for rspec_on_rails"
klass.new(:rspec_on_rails) do |t|
t.spec_opts = ['--options', "\"#{Rails.root}/spec/spec.opts\""]
t.spec_opts = ['--options', Shellwords.escape(Rails.root.join("spec/spec.opts"))]
t.send(spec_files_attr, FileList['vendor/plugins/rspec-rails/spec/**/*/*_spec.rb'])
end
end
@ -153,11 +153,11 @@ unless Rails.env.production? || ARGV.any? { |a| a.start_with?('gems') }
desc "Load fixtures (from spec/fixtures) into the current environment's database. Load specific fixtures using FIXTURES=x,y. Load from subdirectory in test/fixtures using FIXTURES_DIR=z."
task :load => :environment do
ActiveRecord::Base.establish_connection(Rails.env)
base_dir = File.join(Rails.root, 'spec', 'fixtures')
fixtures_dir = ENV['FIXTURES_DIR'] ? File.join(base_dir, ENV['FIXTURES_DIR']) : base_dir
base_dir = Rails.root.join('spec,fixtures')
fixtures_dir = ENV['FIXTURES_DIR'] ? base_dir.join(ENV['FIXTURES_DIR']) : base_dir
require 'active_record/fixtures'
(ENV['FIXTURES'] ? ENV['FIXTURES'].split(",").map { |f| File.join(fixtures_dir, f) } : Dir.glob(File.join(fixtures_dir, '*.{yml,csv}'))).each do |fixture_file|
(ENV['FIXTURES'] ? ENV['FIXTURES'].split(",").map { |f| fixtures_dir.join(f) } : Dir.glob(fixtures_dir.join('*.{yml,csv}'))).each do |fixture_file|
Fixtures.create_fixtures(File.dirname(fixture_file), File.basename(fixture_file, '.*'))
end
end
@ -165,7 +165,7 @@ unless Rails.env.production? || ARGV.any? { |a| a.start_with?('gems') }
end
namespace :server do
daemonized_server_pid = File.expand_path("#{Rails.root}/tmp/pids/spec_server.pid")
daemonized_server_pid = Rails.root.join("tmp/pids/spec_server.pid").expand_path
desc "start spec_server."
task :start do

View File

@ -86,7 +86,7 @@ module Lti
it 'returns a tool_proxy id object' do
course_with_teacher_logged_in(:active_all => true)
tool_proxy_fixture = File.read(File.join(Rails.root, 'spec', 'fixtures', 'lti', 'tool_proxy.json'))
tool_proxy_fixture = Rails.root.join("spec/fixtures/lti/tool_proxy.json").read
json = JSON.parse(tool_proxy_fixture)
json[:format] = 'json'
json[:account_id] = @course.account.id
@ -98,7 +98,7 @@ module Lti
it 'has the correct content-type' do
course_with_teacher_logged_in(:active_all => true)
tool_proxy_fixture = File.read(File.join(Rails.root, 'spec', 'fixtures', 'lti', 'tool_proxy.json'))
tool_proxy_fixture = Rails.root.join("spec/fixtures/lti/tool_proxy.json").read
headers = { 'CONTENT_TYPE' => 'application/vnd.ims.lti.v2.toolproxy+json',
'ACCEPT' => 'application/vnd.ims.lti.v2.toolproxy.id+json' }.merge(oauth1_header)
post "/api/lti/accounts/#{@course.account.id}/tool_proxy.json", params: tool_proxy_fixture, headers: headers
@ -107,7 +107,7 @@ module Lti
it 'returns an error message' do
course_with_teacher_logged_in(:active_all => true)
tool_proxy_fixture = File.read(File.join(Rails.root, 'spec', 'fixtures', 'lti', 'tool_proxy.json'))
tool_proxy_fixture = Rails.root.join("spec/fixtures/lti/tool_proxy.json").read
tp = ::IMS::LTI::Models::ToolProxy.new.from_json(tool_proxy_fixture)
tp.tool_profile.resource_handlers.first.messages.first.enabled_capability = ['extra_capability']
headers = { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' }.merge(oauth1_header)
@ -118,8 +118,8 @@ module Lti
it 'accepts split secret' do
course_with_teacher_logged_in(:active_all => true)
# tool_proxy_fixture = File.read(File.join(Rails.root, 'spec', 'fixtures', 'lti', 'tool_proxy.json'))
tool_proxy_fixture = JSON.parse(File.read(File.join(Rails.root, 'spec', 'fixtures', 'lti', 'tool_proxy.json')))
# tool_proxy_fixture = Rails.root.join("spec/fixtures/lti/tool_proxy.json").read
tool_proxy_fixture = JSON.parse(Rails.root.join("spec/fixtures/lti/tool_proxy.json").read)
tool_proxy_fixture[:enabled_capability] = ['OAuth.splitSecret']
tool_proxy_fixture["security_contract"].delete("shared_secret")
tool_proxy_fixture["security_contract"]["tp_half_shared_secret"] = SecureRandom.hex(128)
@ -154,7 +154,7 @@ module Lti
it 'supports using a specified custom TCP' do
course_with_teacher_logged_in(:active_all => true)
tool_proxy_fixture = File.read(File.join(Rails.root, 'spec', 'fixtures', 'lti', 'tool_proxy.json'))
tool_proxy_fixture = Rails.root.join("spec/fixtures/lti/tool_proxy.json").read
tp = ::IMS::LTI::Models::ToolProxy.new.from_json(tool_proxy_fixture)
tp.tool_profile.product_instance.product_info.product_family.vendor.code = vendor_code
message = tp.tool_profile.resource_handlers.first.messages.first
@ -183,7 +183,7 @@ module Lti
reg_password: 'password',
registration_url: 'http://example.com/register'
})
tool_proxy_fixture = File.read(File.join(Rails.root, 'spec', 'fixtures', 'lti', 'tool_proxy.json'))
tool_proxy_fixture = Rails.root.join("spec/fixtures/lti/tool_proxy.json").read
tp = ::IMS::LTI::Models::ToolProxy.new.from_json(tool_proxy_fixture)
tp.tool_profile.product_instance.product_info.product_family.vendor.code = vendor_code
response = post "/api/lti/accounts/#{@course.account.id}/tool_proxy.json", params: tp.to_json, headers: request_headers
@ -192,7 +192,7 @@ module Lti
it 'returns a 401 if the reg_key is not valid' do
course_with_teacher_logged_in(:active_all => true)
tool_proxy_fixture = File.read(File.join(Rails.root, 'spec', 'fixtures', 'lti', 'tool_proxy.json'))
tool_proxy_fixture = Rails.root.join("spec/fixtures/lti/tool_proxy.json").read
json = JSON.parse(tool_proxy_fixture)
json[:format] = 'json'
json[:account_id] = @course.account.id
@ -231,8 +231,8 @@ module Lti
allow(OAuth::Signature).to receive(:build).and_return(mock_siq)
course_with_teacher_logged_in(:active_all => true)
fixture_file = File.join(Rails.root, 'spec', 'fixtures', 'lti', 'tool_proxy.json')
tool_proxy_fixture = JSON.parse(File.read(fixture_file))
fixture_file = Rails.root.join('spec/fixtures/lti/tool_proxy.json')
tool_proxy_fixture = JSON.parse(fixture_file.read)
tcp_url = polymorphic_url([@course.account, :tool_consumer_profile])
tool_proxy_fixture["tool_consumer_profile"] = tcp_url

View File

@ -119,8 +119,8 @@ module Lti
course_with_teacher(active_all: true, user: user_with_pseudonym, account: account)
tp = create_tool_proxy(context: @course)
fixture_file = File.join(Rails.root, 'spec', 'fixtures', 'lti', 'tool_proxy.json')
tool_proxy_fixture = JSON.parse(File.read(fixture_file))
fixture_file = Rails.root.join("spec/fixtures/lti/tool_proxy.json")
tool_proxy_fixture = JSON.parse(fixture_file.read)
tool_proxy_fixture[:tool_proxy_guid] = tp.guid
tp.update_attribute(:update_payload, {
@ -152,8 +152,8 @@ module Lti
course_with_teacher(active_all: true, user: user_with_pseudonym, account: account)
tp = create_tool_proxy(context: @course)
fixture_file = File.join(Rails.root, 'spec', 'fixtures', 'lti', 'tool_proxy.json')
tool_proxy_fixture = JSON.parse(File.read(fixture_file))
fixture_file = Rails.root.join("spec/fixtures/lti/tool_proxy.json")
tool_proxy_fixture = JSON.parse(fixture_file.read)
tool_proxy_fixture[:tool_proxy_guid] = tp.guid
tp.update_attribute(:update_payload, {
@ -222,8 +222,8 @@ module Lti
course_with_teacher(active_all: true, user: user_with_pseudonym, account: account)
tp = create_tool_proxy(context: @course)
fixture_file = File.join(Rails.root, 'spec', 'fixtures', 'lti', 'tool_proxy.json')
tool_proxy_fixture = JSON.parse(File.read(fixture_file))
fixture_file = Rails.root.join("spec/fixtures/lti/tool_proxy.json")
tool_proxy_fixture = JSON.parse(fixture_file.read)
tool_proxy_fixture[:tool_proxy_guid] = tp.guid
tp.update_attribute(:update_payload, {

View File

@ -65,7 +65,7 @@ describe "Modules API", type: :request do
end
before do
@attachment = attachment_model(:context => @course, :usage_rights => @course.usage_rights.create!(legal_copyright: '(C) 2012 Initrode', use_justification: 'creative_commons', license: 'cc_by_sa'), :uploaded_data => stub_file_data("test_image.jpg", File.read(Rails.root + "spec/fixtures/test_image.jpg"), "image/jpeg"))
@attachment = attachment_model(:context => @course, :usage_rights => @course.usage_rights.create!(legal_copyright: '(C) 2012 Initrode', use_justification: 'creative_commons', license: 'cc_by_sa'), :uploaded_data => stub_file_data("test_image.jpg", Rails.root.join("spec/fixtures/test_image.jpg").read, "image/jpeg"))
@attachment_tag = @module2.add_item(:id => @attachment.id, :type => 'attachment')
@module2.save!

View File

@ -59,7 +59,7 @@ describe ContentExportsController do
describe 'GET xml_schema' do
describe 'with a valid file' do
let(:filename) { 'cccv1p0' }
let(:full_path) { Rails.root + "lib/cc/xsd/#{filename}.xsd" }
let(:full_path) { Rails.root.join("lib/cc/xsd/#{filename}.xsd") }
before { get 'xml_schema', params: { :version => filename } }

View File

@ -40,7 +40,7 @@ describe ExternalContentController do
lti_message_type: 'ContentItemSelection',
lti_version: 'LTI-1p0',
data: '',
content_items: File.read(File.join(Rails.root, 'spec', 'fixtures', 'lti', 'content_items.json')),
content_items: Rails.root.join('spec/fixtures/lti/content_items.json').read,
lti_msg: 'some lti message',
lti_log: 'some lti log',
lti_errormsg: 'some lti error message',
@ -123,7 +123,7 @@ describe ExternalContentController do
{
lti_message_type: 'ContentItemSelection',
lti_version: 'LTI-1p0',
content_items: File.read(File.join(Rails.root, 'spec', 'fixtures', 'lti', 'content_items.json')),
content_items: Rails.root.join('spec/fixtures/lti/content_items.json').read,
data: Canvas::Security.create_jwt({ content_item_id: service_id, oauth_consumer_key: oauth_consumer_key }),
lti_msg: '',
lti_log: '',
@ -203,7 +203,7 @@ describe ExternalContentController do
post(:success, params: { service: 'external_tool_dialog', course_id: c.id, lti_message_type: 'ContentItemSelection',
lti_version: 'LTI-1p0',
data: '',
content_items: File.read(File.join(Rails.root, 'spec', 'fixtures', 'lti', 'content_items_2.json')),
content_items: Rails.root.join('spec/fixtures/lti/content_items_2.json').read,
lti_msg: '',
lti_log: '',
lti_errormsg: '',
@ -217,7 +217,7 @@ describe ExternalContentController do
it "uses the default url if one isn't provided" do
c = course_factory
json = JSON.parse(File.read(File.join(Rails.root, 'spec', 'fixtures', 'lti', 'content_items_2.json')))
json = JSON.parse(Rails.root.join('spec/fixtures/lti/content_items_2.json').read)
json['@graph'][0].delete('url')
launch_url = 'http://example.com/launch'
post(:success, params: { service: 'external_tool_dialog', course_id: c.id, lti_message_type: 'ContentItemSelection',
@ -236,7 +236,7 @@ describe ExternalContentController do
context 'lti_links' do
it "generates a canvas tool launch url" do
c = course_factory
json = JSON.parse(File.read(File.join(Rails.root, 'spec', 'fixtures', 'lti', 'content_items.json')))
json = JSON.parse(Rails.root.join('spec/fixtures/lti/content_items.json').read)
post(:success, params: { service: 'external_tool_dialog', course_id: c.id, lti_message_type: 'ContentItemSelection',
lti_version: 'LTI-1p0',
content_items: json.to_json })
@ -248,7 +248,7 @@ describe ExternalContentController do
it "generates a borderless launch url for iframe target" do
c = course_factory
json = JSON.parse(File.read(File.join(Rails.root, 'spec', 'fixtures', 'lti', 'content_items.json')))
json = JSON.parse(Rails.root.join('spec/fixtures/lti/content_items.json').read)
json['@graph'][0]['placementAdvice']['presentationDocumentTarget'] = 'iframe'
post(:success, params: { service: 'external_tool_dialog', course_id: c.id, lti_message_type: 'ContentItemSelection',
lti_version: 'LTI-1p0',
@ -260,7 +260,7 @@ describe ExternalContentController do
it "generates a borderless launch url for window target" do
c = course_factory
json = JSON.parse(File.read(File.join(Rails.root, 'spec', 'fixtures', 'lti', 'content_items.json')))
json = JSON.parse(Rails.root.join('spec/fixtures/lti/content_items.json').read)
json['@graph'][0]['placementAdvice']['presentationDocumentTarget'] = 'window'
post(:success, params: { service: 'external_tool_dialog', course_id: c.id, lti_message_type: 'ContentItemSelection',
lti_version: 'LTI-1p0',

View File

@ -123,7 +123,7 @@ module ErrorContext
end
def base_error_path
@base_error_path ||= ENV.fetch("ERROR_CONTEXT_BASE_PATH", Rails.root.join("log", "spec_failures", "Initial"))
@base_error_path ||= ENV.fetch("ERROR_CONTEXT_BASE_PATH", Rails.root.join("log/spec_failures/Initial"))
end
end

View File

@ -179,7 +179,7 @@ describe ExternalToolsController do
allow_any_instance_of(AppCenter::AppApi).to receive(:fetch_app_center_response).and_return(app_center_response)
allow_any_instance_of(CC::Importer::BLTIConverter).to receive(:fetch).and_return(config_response)
configxml = File.read(File.join(Rails.root, 'spec', 'fixtures', 'lti', 'config.youtube.xml'))
configxml = Rails.root.join('spec/fixtures/lti/config.youtube.xml').read
stub_request(:get, app_center_response['config_xml_url']).to_return(body: configxml)
stub_request(:get, "https://www.edu-apps.org/tool_i_should_not_have_access_to.xml").to_return(status: 404)
end

View File

@ -22,7 +22,7 @@ describe ApiScopeMapperFallback do
let(:resource) { "users" }
it "loads the ApiScopeMapper file if present" do
if File.exist?(Rails.root.join('lib/api_scope_mapper.rb'))
if Rails.root.join('lib/api_scope_mapper.rb').file?
expect(ApiScopeMapper.name).not_to eq(ApiScopeMapperFallback.name)
else
expect(ApiScopeMapper.name).to eq(ApiScopeMapperFallback.name)

View File

@ -39,7 +39,7 @@ module Lti
{
lti_message_type: 'ContentItemSelection',
lti_version: 'LTI-1p0',
content_items: File.read(File.join(Rails.root, 'spec', 'fixtures', 'lti', 'content_items.json')),
content_items: Rails.root.join('spec/fixtures/lti/content_items.json').read,
data: Canvas::Security.create_jwt({ content_item_id: "3" }),
lti_msg: '',
lti_log: '',

View File

@ -176,7 +176,7 @@ describe AuthenticationProvider::SAML do
end
it "interprets relative paths from the config dir" do
expect(AuthenticationProvider::SAML.resolve_saml_key_path('initializers')).to eq Rails.root.join('config', 'initializers').to_s
expect(AuthenticationProvider::SAML.resolve_saml_key_path('initializers')).to eq Rails.root.join('config/initializers').to_s
end
end

View File

@ -110,8 +110,8 @@ describe BigBlueButtonConference do
end
describe 'plugin setting recording_enabled is enabled' do
let(:get_recordings_fixture) { File.read(Rails.root.join('spec', 'fixtures', 'files', 'conferences', 'big_blue_button_get_recordings_two.json')) }
let(:get_recordings_bulk_fixture) { File.read(Rails.root.join('spec', 'fixtures', 'files', 'conferences', 'big_blue_button_get_recordings_bulk.json')) }
let(:get_recordings_fixture) { Rails.root.join('spec/fixtures/files/conferences/big_blue_button_get_recordings_two.json').read }
let(:get_recordings_bulk_fixture) { Rails.root.join('spec/fixtures/files/conferences/big_blue_button_get_recordings_bulk.json').read }
before do
allow(WebConference).to receive(:plugins).and_return([

View File

@ -29,7 +29,7 @@ module Lti
let(:tool_proxy_service) { ToolProxyService.new }
describe '#process_tool_proxy_json' do
let(:tool_proxy_fixture) { File.read(File.join(Rails.root, 'spec', 'fixtures', 'lti', 'tool_proxy.json')) }
let(:tool_proxy_fixture) { Rails.root.join('spec/fixtures/lti/tool_proxy.json').read }
let(:tool_proxy_guid) { 'guid' }
let(:account) { Account.new }

View File

@ -18,7 +18,7 @@
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
describe Rails.root.join('app', 'jsx', 'shared', 'components', 'TimeZoneSelect', 'localized-timezone-lists') do
describe Rails.root.join('app/jsx/shared/components/TimeZoneSelect/localized-timezone-lists') do
it("each json file should match ruby data for that locale") do
def localized_timezones(zones)
zones.map { |tz| { name: tz.name, localized_name: tz.to_s } }

View File

@ -263,7 +263,7 @@ describe 'Developer Keys' do
end
context "scopes" do
unless File.exist?(Rails.root.join('lib/api_scope_mapper.rb'))
unless Rails.root.join('lib/api_scope_mapper.rb').file?
before do
stub_const("ApiScopeMapper", Class.new do
def self.lookup_resource(controller, _action)

View File

@ -298,7 +298,7 @@ describe "Gradebook" do
f('[data-menu-item-id="reupload-submissions"]').click
# When I attach a submissions zip file
fixture_file = Rails.root.join('spec', 'fixtures', 'files', 'submissions.zip')
fixture_file = Rails.root.join('spec/fixtures/files/submissions.zip')
f('input[name=submissions_zip]').send_keys(fixture_file)
# And I upload it

View File

@ -340,11 +340,11 @@ RSpec::Expectations.configuration.on_potential_false_positives = :raise
require 'rspec_junit_formatter'
RSpec.configure do |config|
config.example_status_persistence_file_path = Rails.root.join('tmp', "rspec#{ENV.fetch('PARALLEL_INDEX', '0').to_i}")
config.example_status_persistence_file_path = Rails.root.join("tmp/rspec#{ENV.fetch('PARALLEL_INDEX', '0').to_i}")
config.fail_if_no_examples = true
config.use_transactional_fixtures = true
config.use_instantiated_fixtures = false
config.fixture_path = Rails.root.join('spec', 'fixtures')
config.fixture_path = Rails.root.join('spec/fixtures')
config.infer_spec_type_from_file_location!
config.raise_errors_for_deprecations!
config.color = true
@ -911,7 +911,7 @@ module I18nStubs
end
LazyPresumptuousI18nBackend.prepend(I18nStubs)
Dir[Rails.root + '{gems,vendor}/plugins/*/spec_canvas/spec_helper.rb'].sort.each { |file| require file }
Dir[Rails.root.join('{gems,vendor}/plugins/*/spec_canvas/spec_helper.rb')].sort.each { |file| require file }
Shoulda::Matchers.configure do |config|
config.integrate do |with|