text
stringlengths
10
2.61M
require 'spec_helper' describe Typhoeus::Request do let(:url) { "http://www.google.com" } let(:options) { {} } let(:request) { Typhoeus::Request.new(url, options) } describe "#inspect" do let(:url) { "http://www.google.com" } let(:options) do { :body => "a=1&b=2", :params => { :c => 'ok'...
FactoryGirl.define do factory :evidence do url "https://www.test.com" support true source factory :supporting_evidence do support true end factory :refuting_evidence do support false end end end
class UserProfile < ApplicationRecord attr_accessor :skip_validation belongs_to :user validates :first_name, presence: true, length: { in: 2..12 }, unless: :skip_validation validates :last_name, presence: true, length: { in: 2..12 }, unless: :skip_validation validates :zip_code, presence: true, unless: :skip...
class AddAddress2IsYardToUsers < ActiveRecord::Migration def change add_column :users, :address2, :string add_column :users, :is_yard, :boolean, default: false end end
# Copyright (C) 2014 Jan Rusnacko # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of the # MIT license. require 'rspec/expectations' describe 'hash with constraints' do let(:hashc) do { :a => 1, 'b' => { c: 2 }, 'd'...
# frozen_string_literal: true # Shop class Shop < ActiveRecord::Base include ShopifyApp::SessionStorage include ShopifyHelper def products fetch_products end def collections fetch_collections end def api_version ShopifyApp.configuration.api_version end private def fetch_products ...
class EmailType < ActiveRecord::Base attr_accessible :description, :name, :created_by, :updated_by validates :name, :presence => true, :length => { :minimum => 1 } has_many :emails end # == Schema Information # # Table name: email_types # # id :integer not null, primary key # name :strin...
class View < ActiveRecord::Base has_one :filter belongs_to :user after_save :create_filter accepts_nested_attributes_for :filter # # Parses the associated filters and renders the log entries # def render LogEntry.all(:reversed => true) if filter.property.empty? || filter.query_type.empty? cas...
class Post attr_reader :title attr_accessor :author #just putting this here allows them to access my author class apparently. @@all = [] #this represents all instances of Post def initialize @@all << self end def self.all @@all end def title=(title) @title = title end # def author # Author...
class PresidentImagesController < ApplicationController before_action :set_company before_action :set_president, only: %i[create update destroy] def new; end def edit; end def update @president.update_attribute(:image, params.permit(:image, :image_cache, :remove_image)) redirect_to company_path(@co...
#require all form elements here module Page module Form include Element include HttpRequestor def submit(*options) request_type = (options[0].is_a?(String) && options[0]) || self.request_method form_values = options.last if options.last.is_a?(Hash) # get and override form valu...
# frozen_string_literal: true require 'graphql/tracing/notifications_tracing' module GraphQL module Tracing # This implementation forwards events to ActiveSupport::Notifications # with a `graphql` suffix. # # @see KEYS for event names module ActiveSupportNotificationsTracing # A cache of f...
require_relative "./encryptor" require 'optparse' options = {} OptionParser.new do |opts| opts.on('-r', '--rotation NUM', Integer) do |num| options[:rotation] = num end opts.on('-f', '--file NAME') do |name| options[:file] = name end opts.on('-d', '--decrypt') do |d| options[:decrypt] = d en...
class User < ApplicationRecord mount_uploader :avatar, AvatarUploader # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable has_many :reviews has_many :restaurants validates :first_name, presence: true validates :last_name, presence: true vali...
class MessagesController < ApplicationController def create from_number = params['From'] raw_message = params['Body'] command, message = raw_message.split(' ', 2) command = command.downcase message = message.strip if message case command when "setup" handle_setup(from_number) w...
require 'pry' class Player attr_accessor :name, :move, :wins # Constructs the initial state of the Player object # # +name: a string representing the name of the player # @move and @wins instance variables def initialize(name:) @name = name @move = nil @wins = 0 end def input(acceptable...
require 'rails_helper' RSpec.describe InvoiceItem, type: :model do describe 'validations' do it { should define_enum_for(:status).with_values(pending: 0, packaged: 1, shipped: 2) } it { should validate_presence_of(:quantity) } it { should validate_presence_of(:unit_price) } it { should validate_prese...
Gem::Specification.new do |s| s.name = 'korekto' s.version = '1.6.210409' s.homepage = 'https://github.com/carlosjhr64/korekto' s.author = 'carlosjhr64' s.email = 'carlosjhr64@gmail.com' s.date = '2021-04-09' s.licenses = ['MIT'] s.description = <<DESCRIPTION A general proof checker. ...
class EpaysController < ApplicationController def index @epays = HTTParty.get('https://sandbox.usaepay.com/api/v2/transactions', headers: { 'Content-Type' => 'application/json', 'Authorization' => "Basic #{Rails.application.credentials.usaepay[:authkey]}" } ) end def select ...
require 'transaction_history' describe TransactionHistory do let(:trans) { double :transaction } let(:date) { '2001-02-01' } let(:amount) { 25 } let(:balance) { 30 } let(:transaction_class) { double :transaction_class, new: trans } let(:history) { described_class.new(transaction_class: transaction_class) ...
class Visitor < ActiveRecord::Base #Before actions before_save { self.email = email.downcase } #Pattern for email valid_email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i #Relations in db has_many :visits, dependent: :destroy belongs_to :employee #Valid...
class CreateMovieNights < ActiveRecord::Migration def self.up create_table :movie_nights do |t| t.string :users t.text :movies_towatch t.text :movies_seen t.timestamps end end def self.down drop_table :movie_nights end end
# Copyright (C) 2014 Jan Rusnacko # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of the # MIT license. require 'ruby_util/hash_with_method_access' require 'ruby_util/hash_with_constraints' require 'date' # Xenuti::Report...
class IncomeStatement include ActiveModel::Model def initialize(forecast, opts = {}) @forecast = forecast @options = opts @start_date = @forecast.forecast_start_date @end_date = @start_date + 60.months @accounts_totals = AccountTotals.new(forecast, frequency) end def revenues @forecast....
require "uri" require "net/http" require "net/https" module Horseman class Connection attr_reader :http, :uri def url=(url) @uri = URI.parse(url) build_http end def exec_request(request) @http.request(request) end def build_request(options={}) self.url = opti...
class ChangeHypenToUnderscore < ActiveRecord::Migration[5.2] def change rename_column :products, "gluten-free", :gluten_free rename_column :products, "dairy-free", :dairy_free end end
Pod::Spec.new do |s| s.name = "JMBaseKit" s.version = "2.0.4" s.summary = "JMBaseKit." s.description = <<-DESC 基础框架,方便集成,pods 管理 常用宏定义 JMApplication 系统功能单列调用 2.0.4 添加UITextView placeholder 添...
# frozen_string_literal: true module Vedeu module Repositories # Some classes expect a certain set of attributes when # initialized, this module uses the #defaults method of the class # to provide missing attribute keys (and values). # # @api private # module Defaults include Ved...
class DetailController < ApplicationController def update detail = Detail.find(params[:id]) detail.update(detail_params) redirect_to admin_user_show_path(detail.user_id) end private def detail_params params.require(:detail).permit(:user_id,:item_id,:price,:count,:order_id,:active) end end
require_relative 'input' class Computer def initialize(tape) @tape = tape.dup @pc = 0 end def has_run? @has_run ||= false end # This is a clean way of storing information about our various commands. def commands @@commands ||= { 1 => {:word => :add, :inc => 4}, 2 => {:word => ...
class Item < ApplicationRecord belongs_to :invoice belongs_to :service delegate :name, to: :service validates :invoice, presence: true validates :price, numericality: { greater_than_or_equal_to: 0 } validates :service, presence: true def as_json(opt = {}) opt.m...
class ApplicationController < ActionController::Base protect_from_forgery with: :exception # Whitelist the following form fields so that we can process them, if coming # from a devise signup form before_action :configure_permitted_parameters, if: :devise_controller? # rescue_from CanCan::AccessDenied do...
pg_hba_conf_file = input('pg_hba_conf_file') approved_auth_methods = input('approved_auth_methods') control "V-72849" do title "PostgreSQL must integrate with an organization-level authentication/access mechanism providing account management and automation for all users, groups, roles, and any other principals....
class AddImageMetaDataToEmoji < ActiveRecord::Migration def change remove_column :emojis, :img add_column :emojis, :filename, :string add_column :emojis, :content_type, :string add_column :emojis, :img_binary, :binary, :limit => 500.kilobytes end end
class ProviderProduct < ApplicationRecord belongs_to :provider belongs_to :product end
require 'spec_helper' describe "Technology" do subject { page } let(:user) { create(:user) } before do sign_in user visit technologies_path end describe "list" do it { should have_selector("title", :text => "Technologies") } it { should have_selector("h2", :text => "Technologies") } it...
#!/usr/bin/env ruby # :title: Plan-R Command Line Application =begin rdoc (c) Copyright 2016 Thoughtgang <http://www.thoughtgang.org> =end require 'plan-r/application' require 'ostruct' require 'optparse' require 'plan-r/content_repo' module PlanR =begin rdoc A generic command-line application. CLI utilities should...
require "docking_station" describe DockingStation do describe "initialization" do it "should have the capacity of 20" do expect(subject.capacity).to eq (20) end end describe "release_bike" do it 'Should return an error when there is no bike to release' do expect { subject.release_bi...
require 'minitest/autorun' require 'minitest/pride' require 'faraday' require './lib/request_handler' class RequestHandlerTest < Minitest::Test def test_it_exists skip rh = RequestHandler.new assert_instance_of RequestHandler, rh end def test_it_displays_headers_on_root_call response = Fara...
# U2.W6: Create a BoggleBoard Class # I worked on this challenge [by myself]. # 2. Pseudocode # establish class BoggleBoard # Define initialize which accepts one argument, dice_grid # Define an instance of dice_grid set equal to dice_grid # End initialize method # Define method print_board # for num in 0....
class Userstore < ApplicationRecord validates :user_id, :uniqueness => { :scope => :store_id } belongs_to :user belongs_to :store end
class UpdateUsersRoleIdTo3 < ActiveRecord::Migration[5.1] def change User.update_all(role_id:3) end end
require "application_system_test_case" class PersonTypesTest < ApplicationSystemTestCase setup do @person_type = person_types(:one) end test "visiting the index" do visit person_types_url assert_selector "h1", text: "Person Types" end test "creating a Person type" do visit person_types_url ...
module Hydra::Works class RemoveRelatedObjectFromCollection ## # Remove a related object from a collection. # # @param [Hydra::Works::Collection] :parent_collection from which to remove the related object # @param [Hydra::PCDM::Object] :child_related_object being removed # # @return [Hydr...
class User < ApplicationRecord validates :name, presence:true, length: {minimum:3, maximum:30} devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :favorites, dependent: :destroy has_many :favorite_movies, through: :favorites, source: :movie has_many :...
require "spec_helper" require 'capybara/poltergeist' Capybara.javascript_driver = :poltergeist feature "Finding address and Commenting on them" do background do visit "/" end scenario "Searching for a house that exists", js: true do click_link "House" fill_in "Address", with: "539 University Avenue"...
module Sumac # Raised by the local endpoint when trying to perform an action on a closed object request broker. class ClosedObjectRequestBrokerError < Error def initialize(message = 'object request broker has closed') super end end end
# This method will return an array of arrays. # Each subarray will have strings which are anagrams of each other # Time Complexity: O(n) where n is the number of elements in the array # Space Complexity: O(n) def grouped_anagrams(strings) return [] if strings.length == 0 hash = {} strings.each do |word| s...
# RELEASE 2: NESTED STRUCTURE GOLF # Hole 1 # Target element: "FORE" array = [[1,2], ["inner", ["eagle", "par", ["FORE", "hook"]]]] # attempts: # ============================================================ p array[1][1][2][0] # ============================================================ # Hole 2 # Target element...
class CreatePublicationDates < ActiveRecord::Migration def self.up create_table :publication_dates do |t| t.integer :query_id t.integer :year t.integer :publication_count t.timestamps end add_index :publication_dates, :query_id end def self.down drop_table :publication_da...
require 'open3' require_relative './util' class Heroku # Will return false if not logged in def self.authed? system( 'heroku', 'auth:token', out: File::NULL, # send output to /dev/null err: File::NULL, # send stderr to /dev/null ) end # Logs in Heroku CLI client def self.login(ema...
require 'test_helper' class AccountActivationsControllerTest < ActionDispatch::IntegrationTest setup do post signup_path, params: { user: { name: 'Albert', surname: 'Einstein', email: 'genius@example.com', password: 'pas...
class Order < ActiveRecord::Base # Associations # ------------ has_many :paypal_transactions # Validations # ----------- validates :description, presence: true validates :amount, presence: true, numericality: { greater_than: 0.00 } validates :quantity, presence: true, numericality: { greater_than: 0, ...
class Api::SessionsController < ApplicationController before_action :authenticate, except: :create respond_to :json def create @user = User.find_by(email: params[:email]).try(:authenticate, params[:password]) if @user secureToken = SecureRandom.uuid @user.update(auth_token: secureToken) ...
require 'minitest/autorun' require_relative 'bowling_game' class BowlingGameTest < MiniTest::Unit::TestCase def setup @game = BowlingGame.new end def test_all_gutter_game record_many_shots(20,0) assert_equal 0, @game.score end def test_all_one_pin record_many_shots(20, 1) assert_equal 20, @game.score e...
require 'test/unit/assertions' include Test::Unit::Assertions def assert_settings(name, expected, arg = nil) actual = get_setting(name, arg) assert_equal(expected, actual) end def get_setting(name, arg = nil) case name when 'Preferences' $fixture.preferences.getPreferences when 'DolphinPrincipal' ...
module Apress module Images class UpdateDuplicateImageJob include Resque::Integration queue :images def self.perform(id, class_name) model = class_name.camelize.constantize image = model.where(id: id).first! return unless image.processing? parent = model.where...
require "rails_helper" RSpec.describe TheaterScreensController, type: :routing do describe "routing" do it "routes to #index" do expect(:get => "/theater_screens").to route_to("theater_screens#index") end it "routes to #new" do expect(:get => "/theater_screens/new").to route_to("theater_scr...
# frozen_string_literal: true # Preview all emails at http://localhost:3000/rails/mailers/job_failure_notice_mailer class JobFailureNoticeMailerPreview < ActionMailer::Preview def alert exception = OandaAPI::RequestError.new('An error as occured while processing response.') backtrace = [ '..lib/oanda_a...
require_relative('../db/sql_runner') class Customer attr_reader :id attr_accessor :name, :funds def initialize(options) @name = options['name'] @funds = options['funds'].to_i() @id = options['id'].to_i() if options ['id'] end def save() sql = "INSERT INTO customers ( name, ...
class Course < ApplicationRecord validates :name, presence: true validates :school, presence: true validates :description, presence: true validates :teacher, presence: true validates :lat, presence: true validates :lng, presence: true validates :start_date, presence: true validates :end_date, presence: ...
class User < ActiveRecord::Base validates :uname, uniqueness: true mount_uploader :avatar, AvatarUploader end
# 3-SUM in quadratic time. Design an algorithm for the 3-SUM problem that takes # time proportional to n2 in the worst case. You may assume that you can sort the # n integers in time proportional to n2 or better. #First sort the array #Then a pointer to left pole, right pole, and start #Computes vals in O(n^2) time, f...
require 'coveralls' Coveralls.wear! require 'leakybucket' describe Leakybucket::Bucket do it 'should creates leaky bucket' do l1 = Leakybucket::Bucket.new(limit: 3) l1.value.should eql(3) l2 = Leakybucket::Bucket.new(limit: 5) l2.value.should eql(5) l3 = Leakybucket::Bucket.new l3.value.shou...
class ChangeSlogTypeColumnName < ActiveRecord::Migration # lol. type is a reserved keyword in ruby def change rename_column :slogs, :type, :slog_type end end
require 'rails_helper' describe 'admin/case_studies/show' do let(:title) { 'Give Cat' } let(:intro) { 'A little intro' } let(:body) { 'A bit of body' } let(:case_study) do create(:case_study, title: title, intro: intro, body: body) end before do assign(:case...
class User < ApplicationRecord petergate(roles: [:admin, :editor], multiple: false) devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :questions, dependent: :destroy has_many :answers, dependent: :destroy end
class Note < ActiveRecord::Base include PgSearch has_attached_file :image, :styles => { :medium => "300x300" } validates :notebook_id, :title, presence: true # validates :image, :attachment_presence => true validates_attachment :image, :content_type => { :content_type => ['image/jpeg', 'image/jpg', 'image...
require 'csv' require_relative '../lib/csv_handler' require_relative '../lib/transaction' class TransactionRepository attr_reader :transactions, :engine def initialize(engine, params) @engine = engine @transactions = params.collect {|row| Transaction.new(row, self)} end def all transactions end...
require 'rails_helper' RSpec.describe Relationship, type: :model do let(:relationship) { FactoryBot.create(:relationship) } describe 'フォロー機能' do context "フォローできる時" do it 'user_idとcat_idがあればフォローできる' do expect(relationship).to be_valid end it '同じcat_idでもuser_idが異なればフォローできる' do ...
# lib/controllers/mixins/user_actions.rb require 'controllers/mixins/actions_base' require 'models/user' module Mithril::Controllers::Mixins # Actions for registering a new user, or for logging in as an existing user. module UserActions extend ActionMixin mixin ActionsBase def allow_registrati...
class RenameShiftNameToLabel < ActiveRecord::Migration[6.0] def change rename_column :shifts, :name, :label end end
class Operator def initialize(mars_rover) @mars_rover = MarsRover.new end def receive_commands(commands) commands.each do |command| case command when command == 'L' @mars_rover.turn_left when command == 'R' @mars_rover.turn_right when comman...
# frozen_string_literal: true class User < ApplicationRecord has_secure_password has_many :blogs, dependent: :destroy validates :email, :username, :password, presence: true validates :username,uniqueness: true, :length=> {:minimum=>2} validates :password, :length => { :in => 8..20 } validates :...
class RenameExcerciseWorkoutIdToWorkoutGroupId < ActiveRecord::Migration[5.1] def change rename_column :exercises, :workout_id, :workout_group_id end end
require_relative '../../automated_init' context "Output" do context "Error Summary" do context "Finish Run" do result = Controls::Result.example context "Errors" do output = Output.new output.writer.enable_styling! output.errors_by_file = { 'some_test.rb' => 1, ...
# Problem 145: How many reversible numbers are there below one-billion? # http://projecteuler.net/problem=145 # Some positive integers n have the property that the sum [ n + reverse(n) ] consists entirely of odd (decimal) digits. For instance, 36 + 63 = 99 and 409 + 904 = 1313. We will call such numbers reversible; so...
require_relative "../lib/sesion" RSpec.describe Sesion do # Controla el flujo del juego # por cada sesión tengo un texto guía # la sesión terminar cuando el usuario # tiene la cadena completa y correcta # mostrar el tiempo de la sesión it "con texto guia diferente de vacío o nil" do se...
class AddResourcesToUserBadge < ActiveRecord::Migration def change add_column :user_badges, :resource_id, :integer, null: false, index: true add_column :user_badges, :resource_type, :string, null: false, index: true end end
# Palindromic Substrings =begin Write a method that returns a list of all substrings of a string that are palindromic. That is, each substring must consist of the same sequence of characters forwards as it does backwards. The return value should be arranged in the same sequence as the substrings appear in the string. ...
class DayType < ApplicationRecord belongs_to :employee, foreign_key: 'user_id' has_many :attendances, foreign_key: 'day_type' scope :sorted, -> {order(id: :desc)} private end
module Roleable extend ActiveSupport::Concern included do # ROLES ROLE_ADMIN = 0x1.freeze ROLE_CAST_AND_CREW_ADMIN = 0x2.freeze ROLE_GLOBAL_GROUP_ADMIN = 0x4.freeze ROLE_GLOBAL_FORUM_ADMIN = 0x8.freeze ROLE_NEWS_ADMIN = 0x10.freeze ROLE_PODCAST_ADM...
# A sample Guardfile # More info at https://github.com/guard/guard#readme guard 'coffeescript', input: 'coffee', output: 'public/javascripts' guard 'compass' do watch(%r{^sass/(.*)\.s[ac]ss$}) end guard 'haml', input: 'haml', output: 'public', haml_options: {attr_wrapper: '"'} do watch(%r{^haml/.+(\.html\.haml)$...
class AuthorizeApiRequest def initialize(headers = {}) @headers = headers end # Service entry point - return valid user object def call { visitor: visitor } end private attr_reader :headers def visitor # check if user is in the database # memoize user object register_cl...
# frozen_string_literal: true require "beyond_api/utils" module BeyondApi class NewsletterTarget < Base include BeyondApi::Utils # # A +POST+ request is used to create the newsletter target. Each shop can only have one newsletter target. # You can update this target at any time, or delete the exist...
require "./lib/ahorkado.rb" require "./lib/lista_palabras.rb" describe "Juego de Ahorkado" do it "palabrafija" do ahorkado = Ahorkado.new "prueba" ahorkado.obtener_palabra.should == "PRUEBA" end it "letraEnPalabraError" do ahorkado = Ahorkado.new "prueba" letra = "h" ahorkado.verificar_letra_palabra(le...
require "rails_helper" RSpec.describe "Types::QueryType" do describe "Listings" do let!(:listings) { create_pair(:listing) } let(:query) do %( query{ listings{ title } } ) end subject(:result) do NeighbourlySchema.execute(query).as_j...
# == Schema Information # # Table name: sessions # # id :integer not null, primary key # user_id :integer not null # session_token :string(255) not null # created_at :datetime # updated_at :datetime # environment :string(255) not null # location :string(2...
require 'rails_helper' RSpec.describe Orgadmin::AppealsController, type: :controller do let(:oc) { FactoryGirl.create(:organization_campaign) } before(:each) { login_user; subject.current_user.add_role(:admin, oc.organization) } describe 'new >' do it 'denormalizes variables for fast lookup' do get :n...
require 'test_helper' class UrlJsonCreationTest < ActionDispatch::IntegrationTest include Devise::Test::IntegrationHelpers setup do Settings.enable_logins = true Settings.enable_url_pushes = true Rails.application.reload_routes! @luca = users(:luca) @luca.confirm end teardown do end ...
module Bibliovore class Library def initialize(data, client) @client = client @data = data end def id @data['id'] end def name @data['name'] end def catalog @data['catalog_url'] end def locations @client.get_endpoint("libraries/#{id}/location...
# -*- mode: ruby -*- # vi: set ft=ruby : require 'yaml' guests = YAML.load_file("vagrant/hosts.yml") Vagrant.configure(2) do |config| guests.each do |guest| config.vm.define guest['name'] do |guest_vm| set_box(guest, guest_vm) set_cpus_and_memory(guest, guest_vm) set_private_ip(guest, g...
# exercises # the diff between include and require: # require - run another file, checks if previously run and can refrain, LoadError on failure # include - takes all methods and includes in current, form of extend # require uses $LOAD_PATH to locate short-named files passed to it # basically it looks in a /lib dir.
# Build a class EmailParser that accepts a string of unformatted # emails. The parse method on the class should separate them into # unique email addresses. The delimiters to support are commas (',') # or whitespace (' '). #You should be able to initialize with a list of emails either separated with spaces #*or* sepa...
class Whip < CondimentDecorator attr_reader :beverage def initialize(beverage) @beverage = beverage end def get_description "#{beverage.get_description}, Whip" end def cost 0.10 + beverage.cost end end
# encoding: utf-8 # 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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.cre...
# encoding: utf-8 module TextUtils # make helpers available as class methods e.g. TextUtils.convert_unicode_dashes_to_plain_ascii extend UnicodeHelper extend TitleHelper extend AddressHelper extend StringFilter # adds asciify and slugify end def title_esc_regex( title_unescaped ) puts "...
# encoding: utf-8 # # © Copyright 2013 Hewlett-Packard Development Company, L.P. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights #...
require 'rails_helper' RSpec.describe SitesController, type: :controller do let(:user) { create :user } describe 'GET #index' do let!(:sites) { create_list :site, 3, user: user } before { login user } before { get :index } it 'returns a 200 custom status code' do expect(response).to have_h...
class FactsController < ApplicationController # GET /facts # GET /facts.json def index @facts = Fact.all @facts_json = @facts.map{ |e| {:fact => e}} respond_to do |format| format.html # index.html.erb format.json { render json: @facts_json } end end # GET /facts/1 # GET /facts/...