text stringlengths 10 2.61M |
|---|
# =============================================================================
#
# MODULE : test/test_group_concurrent_queue.rb
# PROJECT : DispatchQueue
# DESCRIPTION :
#
# Copyright (c) 2016, Marc-Antoine Argenton. All rights reserved.
# =====================================================================... |
Hogwarts::Application.routes.draw do
root to: 'houses#index'
resources :houses do
end
resources :students do
end
end
|
module JsonWord
module ToInclude
def check_valid
w = Word.find(:first, :conditions => ["stem=? and pos=?", stem, pos])
if w
self.relevant = w.relevant
else
if count > 10
self.relevant = true
else
self.relevant = false
end
end
self... |
class LandmarksController < ApplicationController
# Question mark after the trailing slash means that slash is optional
get '/landmarks/?' do
if params[:order] == "alpha"
@landmarks = Landmark.all.order(:name)
else
@landmarks = Landmark.all
end
erb :"/landmarks/index"
end
get '/land... |
# ==========================================================================
# Project: Lebowski Framework - The SproutCore Test Automation Framework
# License: Licensed under MIT license (see License.txt)
# ==========================================================================
module Lebowski
module Foundat... |
require 'test_helper'
class ImageHelperView
include Lotus::View
include Lotus::Helpers::AssetTagHelpers
attr_reader :params
def initialize(params)
@params = Lotus::Action::Params.new(params)
end
end
describe Lotus::Helpers::AssetTagHelpers do
let(:view) { ImageHelperView.new(params) }
let(:params... |
#!/usr/bin/env ruby
#
# Read several bib files and merge into one
#
# check the values of:
# date-written-via-bibdump
# date-modified
#
$:.unshift(File.dirname(__FILE__))
require 'bib_library.rb'
require 'papers_library.rb'
require 'getoptlong'
require 'kconv'
require 'date'
$stdout.set_encoding("EUC-JP", "UTF-8... |
class Player
attr_accessor :life, :name
@@player_count = 1
def initialize(life = 3)
print "Player #{@@player_count}, enter your name: "
@name = gets.chomp
@life = life
@@player_count += 1
end
def wrong_answer
@life -= 1
end
end |
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Ch... |
require 'sinatra'
require 'haml'
require 'zipruby'
require 'rufus-scheduler'
require 'securerandom'
require 'logger'
require File.expand_path '../lib/vk.rb', __FILE__
class VkPhotos < Sinatra::Base
configure :development, :production do
enable :logging, :sessions
disable :run
end
not_found { redirect '... |
class SharedPlace < ApplicationRecord
belongs_to :place
belongs_to :friend, class_name: 'User'
end |
require 'csv'
require 'benchmark'
require_relative 'sort.rb'
lengths = [1, 2, 5, 10, 20, 30, 50, 75, 100, 150, 250, 500, 750, 1000, 2500, 5000, 7500, 10000]
methods = ["bubblesort", "gnomesort", "selectionsort", "insertionsort", "shellsort", "radixsortlsd", "quicksort"]
seperator = ","
header = "Random#{seperator}" +... |
module Smite
class Competitor < Smite::Object
def initialize(data)
data['Queue'] = data['name']
super
@data = DataTransform.transform_items(@data)
@data = DataTransform.transform_match_achievements(@data)
@data = DataTransform.transform_match_summary(@data)
end
def to_player... |
Rails.application.routes.draw do
root "leagues#index"
devise_for :users
resources :leagues
end
|
module Rounders
module Handlers
class Handler
include Rounders::Plugins::Pluggable
include Topping::Configurable::Branch
attr_reader :matches, :rounder
class << self
class Event
attr_reader :matcher, :method_name, :event_class
def initialize(event_class, metho... |
class Admin::ProvidersController < AdminController
load_and_authorize_resource
def index
@providers = Kaminari.paginate_array(@providers).page params[:page]
end
def new
end
def create
@provider = Provider.new(provider_params)
if @provider.save
redirect_to admin_provider_path(@provider)
else
... |
require 'calculator'
require 'ostruct'
describe Dodecaphony::Calculator do
it "initializes with a row" do
row = Dodecaphony::Row.new %w[a b b- c c# d d# e f gb g g#]
calc = Dodecaphony::Calculator.new row
expect(calc).to be_kind_of(Dodecaphony::Calculator)
end
it "can provide the original row"... |
require 'rails_helper'
RSpec.describe Event, type: :model do
describe '.processed' do
let!(:unproccessed) { create :event }
let!(:processed) { create :event, :processed }
it do
expect(described_class.processed).to match_array(processed)
end
end
describe '.with_type' do
let!(:event_... |
# spec/support/models/edge.rb
class Edge < Struct.new(:color)
include ActiveModel::Validations
validates :color, :presence => true
end # class
|
require 'spec_helper'
describe Estatic::Generator do
let(:generator) { described_class.new }
describe '.initialize' do
it 'should respond to run' do
expect(generator).to respond_to(:run)
end
it 'should create an `estatic_site` directory' do
generator
expect(File.directory?(estatic_s... |
class AddDisagreementCommentToCandidateProfile < ActiveRecord::Migration
def change
add_column :candidate_profiles, :disagreement_comment, :string
end
end
|
require 'cinch'
require 'yaml'
require 'byebug'
require_relative 'util.rb'
require 'ostruct'
require 'json'
class Hash # https://stackoverflow.com/a/45851976
def to_o
JSON.parse to_json, object_class: OpenStruct
end
end
class PluginMan
include Cinch::Plugin
def initialize(*args)
super
@list = []
... |
require "focuslight"
require "focuslight/config"
require "focuslight/data"
require "sqlite3"
module Focuslight::Init
def self.run
datadir = Focuslight::Config.get(:datadir)
FileUtils.mkdir_p(datadir)
data = Focuslight::Data.new
number_type = data.number_type
graphs_create = <<"SQL"
CREATE TABLE ... |
class Measurement < ActiveRecord::Base
belongs_to :room, dependent: :destroy
end |
module Hypixel
class Session
attr_reader :json, :game_type, :id, :players, :server
def self.from_json(json)
Session.new(json['session'])
end
private
def initialize(json)
@json = json
@game_type = GameType.from_string json['gameType']
@id = json['_id']
@players = json['players'] ||= []
... |
class SubscriptionsController < ApplicationController
def hook
if params["type"] == "invoice.payment_succeeded"
user = User.where(email: params["receipt_email"]).first
user.update_attributes(:role, 'paid')
end
head :ok
end
end |
class RemoveModFromInstructors < ActiveRecord::Migration[5.2]
def change
remove_column :instructors, :mod
end
end
|
# coding: utf-8
$LOAD_PATH.unshift File.expand_path("../lib", __FILE__)
require 'rubygems'
require 'bundler/setup'
desc 'Default: run unit tests.'
task :default => :spec
require "rspec/core/rake_task"
RSpec::Core::RakeTask.new(:spec)
require 'rake/rdoctask'
desc 'Generate documentation for the acts_as_optimistic_loc... |
class CreateNotificationRecipients < ActiveRecord::Migration
def change
create_table :notification_recipients do |t|
t.integer :notification_id
t.integer :user_id
t.string :state
t.timestamps
end
add_index :notification_recipients, :notification_id
add_index :notification_... |
require_relative 'game'
require_relative 'guest'
require_relative 'settings'
class GameMenu
include Settings
GUEST_TURN_MENU = ['1 - Еще', '2 - Себе', '3 - Вскрываемся',
'0 - Закончить партию'].freeze
ROUND_MENU = ['1 - Новая партия', '0 - Выход из игры'].freeze
GAME_MENU = ['1 - Начать но... |
# frozen_string_literal: true
# rubocop:todo all
require 'spec_helper'
describe 'On-demand AWS Credentials' do
require_libmongocrypt
include_context 'define shared FLE helpers'
include_context 'with AWS kms_providers'
let(:client) { ClientRegistry.instance.new_local_client(SpecConfig.instance.addresses) }
... |
FactoryGirl.define do
factory :activity, :class => Refinery::Activities::Activity do
sequence(:name) { |n| "refinery#{n}" }
end
end
|
class UsersController < ApplicationController
require 'uri'
before_action :not_self_page, only: :show
before_action :set_period, only: :show
def show
@data_xxx_days = PowerLevel.get_target_period_array(@period, params[:id])
@user = User.find(params[:id])
end
def rank
case @period = params[:pe... |
class ApplicationController < ActionController::Base
protect_from_forgery
private
before_filter :set_locale
def set_locale
I18n.locale = extract_locale_from_subdomain || I18n.default_locale
end
def extract_locale_from_subdomain
parsed_locale = request.subdomains.first
I18n.available_locales.... |
xml.instruct!
xml.declare! :DOCTYPE, :yml_catalog, :SYSTEM, "shops.dtd"
xml.yml_catalog( date: "#{Date.today.to_s} 0:01") do
xml.shop do
xml.name "Теплицы Медалак"
xml.company "ИП Кузовлев Сергей Владимирович"
xml.url "http://teplicy.medalak.ru/"
xml.currencies do
xml.currency(id:"RUR", rate: "... |
class Player < ActiveRecord::Base
attr_accessible :title
belongs_to :game
has_many :moves
has_many :rounds, through: :moves
validates_uniqueness_of :title, scope: 'game_id'
after_initialize :set_defaults
def set_defaults
self.points = points.presence || 0
end
end
|
require 'test_helper'
class SocialMediaPostsControllerTest < ActionDispatch::IntegrationTest
setup do
@social_media_post = social_media_posts(:one)
end
test "should get index" do
get social_media_posts_url, as: :json
assert_response :success
end
test "should create social_media_post" do
ass... |
# frozen_string_literal: true
register_block {
name 'block_1'
byte_size 128
comment <<~COMMENT
this is block_1.
this block includes six registers.
COMMENT
register_file {
name 'register_file_0'
offset_address 0x00
register {
name 'register_0'
offset_address 0x00
comment... |
module OauthCookieHelper
def env_domain
domain = ENV['COOKIE_DOMAIN'] || 'localhost'
Rails.logger.error("trying to set cookie for #{domain}")
domain == "localhost" ? :all : domain
end
def set_user_cookie(user)
cookies[:so_auth] = { :value => user.id, :domain => env_domain }
end
def remove_u... |
require 'test/unit'
require 'checkersGame.rb'
class Test_checkersGame < Test::Unit::TestCase
def test_Square_error
#test a failure
assert_raise(ArgumentError)\
{mysquare=CheckersGame::Square.new('*',false)}
end
def test_Square_initialization
#test correct initialization
assert_nothing_raised(ArgumentErro... |
json.array!(@modulo_remitentes) do |modulo_remitente|
json.extract! modulo_remitente, :id, :paciente_id, :nombre, :nombre_entidad, :tipo_entidad, :cargo, :ciudad, :departamento, :direccion, :telefono, :email, :fecha_solicitud
json.url modulo_remitente_url(modulo_remitente, format: :json)
end
|
class Picture < ActiveRecord::Base
belongs_to :Post
has_attached_file :image,
:storage => :dropbox,
:dropbox_credentials => "#{Rails.root}/config/dropbox_config.yml",
:dropbox_options => {
:path => proc { |style| "#{style}/#{id}_#{image.original_filename}"}, :unique_filename => true
}
validates_attachment_content... |
#!/bin/env ruby
require 'bundler/setup'
require '../../config/environment.rb'
require 'rest-client'
require '../config.rb'
require 'logger'
require 'rest-client'
PROCESSOR_SCHEDY_URL = "http://schedy-server:3000"
@log = Logger.new(STDOUT)
def lock_resource(params)
@task_id = params["task_id"]
@status = params["sta... |
#
# Cookbook Name:: nginx
# Recipe:: tcp_proxy
#
# Author:: Luka Zakrajsek (<luka@koofr.net>)
#
# Copyright 2012, Koofr
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apac... |
class Client < ActiveRecord::Base
def self.search(query)
if query
find(:all, :conditions => ['full_name LIKE ?', "%#{query}%"]).first
else
nil
end
end
end |
# https://github.com/kylecronin/boggle-ruby/blob/master/board.rb
class Board
def initialize(state)
@xmax = state.size
@ymax = state[0].size
state.each do |row|
raise "Board rows are of varying lengths" if row.size != @ymax
end
@state = state
end
def [](a, b)
@state[a][b]
end
... |
class Crmcomment < ActiveRecord::Base
unloadable
belongs_to :commentable, polymorphic: true
belongs_to :user
validates :commentable, presence: true
validates :user, presence: true
validates :dtime, :comment, presence: true
def self.to_csv(items)
CSV.generate(col_sep: Setting.plugin_redmine_crm['csv... |
require 'active_support/concern'
module TeamValidations
extend ActiveSupport::Concern
included do
validates_presence_of :name
validates_presence_of :slug
validates_format_of :slug, with: /\A[[:alnum:]-]+\z/, message: :slug_format
validates :slug, length: { in: 4..63 }
validates :slug, uniquene... |
class Glow < FPM::Cookery::Recipe
description 'Render markdown on the CLI, with pizzazz!'
name 'glow'
version '0.2.0'
revision '1'
homepage 'https://github.com/charmbracelet/glow'
source "https://github.com/charmbracelet/glow/releases/download/v#{version}/glow_#{version}_linux_x86_64.tar.gz"
sha2... |
class Mechanic
attr_reader :name, :specialty
@@all = []
def initialize(name, specialty)
@name = name
@specialty = specialty
@@all << self
end
def self.all
@@all
end
def cars
Car.all.select { |mech| mech.mechanic == self }
end
def car_owners
cars.map do |car|
car... |
class Teacher < User
#has_and_belongs_to_many :courses, :join_table => 'users_courses', :foreign_key => 'user_id', :uniq => true
#has_many :users, :through => :courses, :uniq => true, :source => :user
def students
my_students = []
courses.each do |course|
my_students += course.students
end
... |
require 'rest-client'
require 'json'
require 'addressable/uri'
require 'addressable/template'
require 'nokogiri'
require 'sanitize'
class QueryProcessor
def self.validate(name, value)
return !!(value =~ /^[\w ]+$/) if name == "query"
return true
end
def self.transform(name, value)
return value.gsub(... |
require 'rails_helper'
describe EquipmentInfo do
describe '#create' do
context 'can save' do
it 'is valid with all items' do
expect(build(:equipment_info)).to be_valid
end
it 'is valid without a building_name' do
expect(build(:equipment_info, building_name: nil)).to be_valid
... |
require File.dirname(__FILE__) + '/text_analyzer.rb'
=begin
Your text analyzer will provide the following basic statistics:
Character count
Character count (excluding spaces)
Line count
Word count
Sentence count
Paragraph count
Average number of words per sentence
Average number of sentences per paragraph
=end
=be... |
# frozen_string_literal: true
RSpec.describe Jsonschema::Generator::Draft07 do
subject(:generator) { described_class.new(json).call }
let(:json) { {}.to_json }
describe 'Success' do
context 'when json is array' do
let(:json) do
[
{
id: '1',
name: 'John',
... |
class VoteOption < ActiveRecord::Base
has_many :votes, dependent: :destroy
has_many :users, through: :votes
belongs_to :poll
validates :title, presence: true
end
|
class Service < ApplicationRecord
belongs_to :barber, class_name: 'User'
has_many :appointments
validates :title, :duration, :price, presence: true
validates :title, length: { maximum: 150 }
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
# need to include the helper manually for a controller
# this gives us access to all session helpers such as logged_i... |
module Ticketing
module Invoice
class EntityRepository < ::BaseRepository
def paids
dataset.where(:payment_ids.ne => [])
end
private
def entity
::Ticketing::Invoice::Entity
end
end
end
end
|
class MoviesController < ApplicationController
before_action :retrieve_movie, only: %i[show edit update destroy]
def index
redirect_to root_path
end
def show
end
def new
@movie = Movie.new
authorize @movie, :create?
end
def create
@movie = Movie.new(movie_params.merge(:user_id => cur... |
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Ch... |
require "./node"
class BinaryTree
def initialize(data=nil)
unless data.nil?
build_tree(data)
else
@root = nil
end
end
# inserts all of the given data into this tree
def build_tree(data)
@root = Node.new(data[0])
data.shift
data.each { |value| @root.insert(value) }
end
... |
# frozen_string_literal: true
class Product < ApplicationRecord
scope :producible, -> { where(producible: true) }
scope :orderable, -> { where(orderable: true) }
has_many :inventory_lines, dependent: :destroy
has_many :product_providers, dependent: :destroy
has_many :external_entities, through: :product_prov... |
class RemoveContentsFromRssEntries < ActiveRecord::Migration
def change
remove_column :rss_entries, :contents
end
end
|
module ApplicationHelper
class NoParagraphRenderer < ::Redcarpet::Render::XHTML
def paragraph(text)
text
end
end
def self.image
require 'redcarpet'
AutoHtml.add_filter(:image).with({:alt => ''}) do |text, options|
r = Redcarpet::Markdown.new(NoParagraphRenderer)
alt = options[... |
# frozen_string_literal: true
require 'rake'
require 'faker'
require 'sendgrid-ruby'
require 'sinatra/activerecord'
require 'sinatra/activerecord/rake'
require_relative './lib/jobs/topic_job'
# require the model(s)
Dir.glob(File
.join(File.expand_path(__dir__), 'db', 'models', '*.rb')).each { |file| require file }
... |
class Company < ActiveRecord::Base
has_many :contacts, inverse_of: :company
validates :name, uniqueness: true, presence: true
end
|
# frozen_string_literal: true
module AgileAllianceService
def self.check_member(email)
url = "#{Figaro.env.agile_alliance_api_host}/check_member/#{email}"
response = HTTParty.get(url, headers: { 'AUTHORIZATION' => Figaro.env.agile_alliance_api_token })
response.present? && JSON.parse(response.body)['memb... |
require 'spec_helper'
describe 'consul_template' do
RSpec.configure do |c|
c.default_facts = {
:architecture => 'x86_64',
:operatingsystem => 'Ubuntu',
:osfamily => 'Debian',
:operatingsystemrelease => '10.04',
:operatingsystemmajrel... |
class ApplicationController < ActionController::Base
before_action :authenticate_request
protect_from_forgery with: :null_session
attr_reader :current_user
include ExceptionHandler
private
def authenticate_request
@current_user = AuthorizeApiRequest.call(request.headers).result
render json: { error... |
# frozen_string_literal: true
Renalware::Diaverum::Engine.routes.draw do
defaults format: :xml do
get "/hospital_units/:unit_id/patients", to: "patients#index", as: :diaverum_patients
get "/hospital_units/:unit_id/patients/:id", to: "patients#show", as: :diaverum_patient
end
end
|
require 'amberbit-config/version'
require 'amberbit-config/errors'
require 'amberbit-config/config'
require 'amberbit-config/hash_struct'
require 'amberbit-config/engine' if defined?(::Rails::Engine)
module AmberbitConfig
# Initialize AppConfig variable with default file path and custom file path if it wasn't set ye... |
module ApplicationHelper
# Returns the full title on a per-page basis.
def full_title(page_title = "")
base_title = "Ruby on Rails Tutorial Sample App"
if page_title.empty?
base_title
else
page_title + " | " + base_title
end
end
# Downcase and remove spaces from email addresses.
... |
class CreateJoinTableOfficerRso < ActiveRecord::Migration[5.0]
def change
create_join_table :officers, :rsos do |t|
t.index [:officer_id, :rso_id]
end
end
end
|
require "spec_helper"
module LabelGen
describe NumberRecord do
context "with an empty db" do
before :each do
DataMapper.auto_migrate!
end
it "has a max number used as specified in the configuration" do
expect(NumberRecord.max_number_used).to eq LabelGen.configuration.max_... |
class Apply < ApplicationRecord
belongs_to :user
belongs_to :job
has_one :company, through: :job
enum status: {Not_receive: 0, Received: 1}
scope :newest_apply, ->{order :created_at}
end
|
require 'curb'
require 'json'
require_relative '../functions'
namespace :juvenile do
desc "Perform a backup"
task :backup, :app do |t, args|
# Get the app
app = args[:app]
# Load the config
config = Functions.load_config
# if there is no app, or it's nil, run all tasks
if !ap... |
require 'mina/bundler'
require 'mina/rails'
require 'mina/git'
set :domain, '94.23.0.49'
set :port, 22
set :repository, 'https://github.com/sgmap/sirene_as_api.git'
set :branch, 'master'
set :deploy_to, '/var/www/sirene_as_api'
set :user, 'deploy' # Username in the server to SSH to.
set :rails_env, 'production'
# ... |
class User < ActiveRecord::Base
after_create :send_mail
private
def send_mail
TestMailer.sidekiq_delay_for(10.minutes, :retry => false, :queue => "low").new_user id
end
end
|
require("./lib/anagram.rb")
require("rspec")
require("pry")
describe "String#anagram" do
it("Recognizes if two words are not anagrams.") do
expect("ruby".anagram("hard")).to(include("This is not an anagram"))
end
it("Recognizes if two words are anagrams.") do
expect("ruby".anagram("bury")).to(include("Th... |
class Category < ActiveRecord::Base
has_many :decks, through: :categorizations
end
|
#
# Cookbook Name:: chef-secrets
# Spec:: default
#
# Copyright (c) 2016 Criteo, All Rights Reserved.
require 'spec_helper'
describe 'chef-secrets::default' do
context 'When all attributes are default, on an unspecified platform' do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new(platform: 'centos',... |
# == Schema Information
#
# Table name: template_packs
#
# id :integer not null, primary key
# zip_container_file_name :string(255)
# zip_container_content_type :string(255)
# zip_container_file_size :integer
# zip_container_updated_at :datetime
# template_id ... |
module Refinery
module Portfolio
class Item < ActiveRecord::Base
translates :title, :caption
class Translation
attr_accessible :locale
end
attr_accessible :title, :caption, :image_id, :gallery_id, :position
validates :gallery_id, :numericality => {:allow_nil => true}
... |
require 'rails_helper'
RSpec.feature 'Sign-up', type: :feature do
scenario 'can visit sign-up page' do
visit '/users/new'
expect(page).to have_content('Sign up with your email address')
end
scenario 'fill-in form and submit' do
name = 'Rick'
email = 'rick@c137.com'
password = 'science'
... |
class MessageCustomizations < ActiveRecord::Migration
include Enumerable
@opts = [
:homepage_ticket_sales_text,
'Homepage message that will take customer to Buy Tickets page; if blank, link to Tickets page won\'t be displayed',
'Buy Tickets',
:string,
:homepage_subscription_sales_text,
... |
Pod::Spec.new do |s|
s.name = "CleverTap-iOS-SDK"
s.version = "3.1.6"
s.summary = "The CleverTap iOS SDK for App Personalization and Engagement."
s.description = <<-DESC
CleverTap is the next generation app engagement platform. It enables marketers to iden... |
require 'test_helper'
class AsteroidesControllerTest < ActionController::TestCase
setup do
@asteroide = asteroides(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:asteroides)
end
test "should get new" do
get :new
assert_response :succ... |
# frozen_string_literal: true
class Tagging < ApplicationRecord
belongs_to :activity
belongs_to :tag
end
|
require_relative 'generators/fibonacci.rb'
require_relative 'evaluators/is_even.rb'
class ConditionalValuesAggregator
def self.aggregate(upto)
new.aggregate(upto)
end
def aggregate(max_value, generator = Generators::Fibonacci.new, evaluator = Evaluators::IsEven.new)
do_aggregate(0, max_value, generator,... |
class Player < ActiveRecord::Base
attr_accessor :slack_username
has_many :team_players
has_many :elos, dependent: :destroy
scope :player, -> { where(type: nil) }
def pro?
elos.any? { |elo| elo.rating >= Elo::PRO_RATING }
end
def starter?
elos.size < Elo::STARTER_BOUNDRY
end
def member_nam... |
describe PersonSpecie do
describe "associations" do
it { is_expected.to belong_to :person }
it { is_expected.to belong_to :specie }
end
end
|
# require 'rails_helper'
#
# RSpec.describe VolunteersController, type: :controller do
# include Devise::Test::ControllerHelpers
#
# before(:each) do
# @request.env["devise.mapping"] = Devise.mappings[:user]
# @current_user = create(:user)
# sign_in @current_user
# end
#
# describe "GET #index" do
#... |
require 'rails_helper'
RSpec.describe "devise/registration/new.html.erb", type: :feature do
describe "User sign in" do
describe "Valid signin data" do
it "Login and Logout" do
user = build(:user, username: "username", password: "somepassword", password_confirmation: "somepassword")
vi... |
=begin
Using the following code,
add an instance method named #rename that renames kitty when invoked.
class Cat
attr_accessor :name
def initialize(name)
@name = name
end
end
kitty = Cat.new('Sophie')
kitty.name
kitty.rename('Chloe')
kitty.name
Expected output:
Sophie
Chloe... |
require 'spec_helper'
include Church
describe 'CHR' do
it "should return its argument's corresponding character" do
expect(CHR[83]).to eq 83.chr
end
end
describe 'ORD' do
it "should return its argument's corresponding ordinal value" do
expect(ORD['q']).to be 'q'.ord
end
end
describe 'CHARS' do
it ... |
class CheckoutService
CART_ATTRIBUTES = %w(customer_id items total total_discount)
def add_item(customer_id, product_sku, product_price)
cart = Cart.find_or_create_by(customer_id: customer_id)
cart.items ||= []
cart.items << {sku: product_sku, price: product_price}
cart.total += product_price
... |
require 'test_helper'
class FoldersControllerTest < ActionController::TestCase
setup do
@folder = folders(:one)
@user = users(:one)
sign_in @user
end
test "should get index" do
skip('Will implement folders in the future')
get :index
assert_response :success
assert_not_nil assigns(:fo... |
class Courier
# twilio webapp api
attr_reader :messages
attr :client, :messages
def initialize(client: Twilio::REST::Client.new(ENV['ACCOUNT_SID'], ENV['AUTH_TOKEN']))
@client = client
end
def send_message(to: "6507418502", body: "Hello there!")
@message = client.messages.create(
:fro... |
require './../lib/connect_four.rb'
describe "Board" do
board = Board.new
it "is always 7 wide" do
expect(board.board.length).to eql(7)
end
it "is always 6 high" do
expect(board.board[0].length).to eql(6)
end
describe "#place" do
it "places a piece in a specified locati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.