What is the default value of use_transactional_fixtures in rspec? - ruby

I am asking this because in the articles I have read so far, concerning rspec and the database_cleaner gem I see the line config.use_transactional_fixtures = false. If I use the database_cleaner gem couldn't I just delete this line?

Found it In rspec-core:
# Used internally and by extension frameworks like rspec-rails, so they
# can add config settings that are domain specific. For example:
#
# RSpec.configure do |c|
# c.add_setting :use_transactional_fixtures,
# :default => true,
# :alias_with => :use_transactional_examples
# end
So, default is true

Related

undefined method `entry_mapping' for nil:NilClass

I am trying to play around with the RODA Ruby web framework based on Rack. However, I am having issues with using Minitest with the framework. RSpec was hectic with it too unlike Rails. I tried to reproduce the error with pry, but I couldn't make sense of it. How should I fix this? I am getting
undefined method `entry_mapping' for nil:NilClass.
Below is the associated code:
Gemfile
gem 'contentful_model', '~> 1.3' # ActiveModel-like wrapper for the Contentful SDKs
group :test do
gem 'capybara'
gem 'minitest', '>= 5.7.0'
gem 'minitest-hooks', '>= 1.1.0'
gem "minitest-global_expectations"
gem "warning"
gem 'pry'
end
models/recipe.rb
require 'contentful_model'
class Recipe < ContentfulModel::Base
self.content_type_id = 'recipe'
def self.all_recipes
all.load!
end
end
app.rb | Tree Routing
require './.env' if File.exist?(".env.rb")
require './config/initializers/contentful_model'
require 'roda'
require './models/recipe'
require 'tilt/sass'
class App < Roda
hash_routes do
view '', 'index'
end
route do |r|
#recipes = Recipe.all_recipes
r.public
r.assets
check_csrf!
r.hash_routes('')
r.get String do |id|
#recipe_details = Recipe.find(id)
next unless #recipe_details
view 'show'
end
end
end
spec/models/spec_helper.rb
ENV["RACK_ENV"] = "test"
require_relative '../../models/recipe'
require_relative '../minitest_helper'
spec/models/recipe_spec.rb
require_relative 'spec_helper'
describe Recipe do
let(:recipes) { Recipe.all_recipes }
describe '.all_recipes' do
it 'return all records with content type recipe' do
recipes = Recipe.all_recipes # undefined method `entry_mapping' for nil:NilClass
expect(recipes).to all must_be Recipe
end
end
end
pry debug
From: /Users/tiwa/RubymineProjects/marley-spoon-roda/spec/models/recipe_spec.rb:27 .all_recipes#test_0001_return all records with content type recipe:
24: it 'return all records with content type recipe' do
25: recipes = Recipe.all_recipes # undefined method `entry_mapping' for nil:NilClass
26: binding.pry
=> 27: expect(recipes).to all must_be Recipe
28: end
[1] pry(#<.all_recipes>)> Recipe.all_recipes
NoMethodError: undefined method `entry_mapping' for nil:NilClass
from /Users/tiwa/.gem/ruby/2.7.1/gems/contentful_model-1.3.0/lib/contentful_model/base.rb:124:in `mapping?'
I see the code in contentful_model-1.3.0/lib/contentful_model/base.rb:124 is:
ContentfulModel.configuration.entry_mapping.key?(#content_type_id)
If error msg is undefined method `entry_mapping' for nil:NilClass then
ContentfulModel.configuration
Is nil
To fix this you need configure ContentfulModel. Something like that:
ContentfulModel.configure do |config|
config.access_token = "your access token in here" # Required
config.preview_access_token = "your preview token in here" # Optional - required if you want to use the preview API
config.management_token = "your management token in here" # Optional - required if you want to update or create content
config.space = "your space id in here" # Required
config.environment = "master" # Optional - defaults to 'master'
config.default_locale = "en-US" # Optional - defaults to 'en-US'
config.options = { # Optional
# Extra options to send to the Contentful::Client and Contentful::Management::Client
# See https://github.com/contentful/contentful.rb#configuration
# Optional:
# Use `delivery_api` and `management_api` keys to limit to what API the settings
# will apply. Useful because Delivery API is usually visitor facing, while Management
# is used in background tasks that can run much longer. For example:
delivery_api: {
timeout_read: 6
},
management_api: {
timeout_read: 100
}
}
end
With this config this call is not more nil
ContentfulModel.configuration
See https://github.com/contentful/contentful_model

ActiveAdmin ForbiddenAttributesError

i am a brand new for Ruby on Rails.
I am using a ActiveAdmin and i have a problem with creating a AdminUser
ActiveModel::ForbiddenAttributesError in Admin::AdminUsersController#create
ActiveModel::ForbiddenAttributesError
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"nvV++6GNTdA/nDzw1iJ6Ii84pZPcv2mzg0PK2Cg9Ag0=",
"admin_user"=>{"email"=>"admin2#example.com"},
"commit"=>"Create Admin user"}*
Rails 4.1.0
activeadmin 1.0.0
ruby 2.1
app/admin/admin_user.rb
ActiveAdmin.register AdminUser do
index do
column :email
column :current_sign_in_at
column :last_sign_in_at
column :sign_in_count
default_actions
end
form do |f|
f.inputs "Admin Details" do
f.input :email
end
f.actions
end
end
app/models/admin_user.rb
class AdminUser < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable
after_create { |admin| admin.send_reset_password_instructions }
def password_required?
new_record? ? false : super
end
end
Gemfile
source 'https://rubygems.org'
gem 'rails', '4.1.0'
gem 'sqlite3'
gem 'sass-rails', '~> 4.0.3'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'activeadmin', github: 'gregbell/active_admin'
gem 'polyamorous', github: 'activerecord-hackery/polyamorous'
gem 'ransack', github: 'activerecord-hackery/ransack'
gem 'formtastic', github: 'justinfrench/formtastic'
gem 'devise'
gem 'sdoc', '~> 0.4.0', group: :doc
config/environments/development.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Sending emails works
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
end
Rails 4 uses strong parameters, which moves attribute whitelisting from the model to the controller. It is necessary to specify the attributes that you would like to be saved in the database. You have not permitted the attributes in your code, which is why you are receiving the ActiveModel::ForbiddenAttributesError.
Refer to the documentation of ActiveAdmin : Setting up Strong Parameters
You can setup strong parameters in the following way, using permit_params method which creates a method called permitted_params, use this method when overriding create or update actions:
ActiveAdmin.register AdminUser do
## ...
permit_params :attr1, :attr2 ## Add this line
end
Replace :attr1, :attr2, etc with the actual attribute names that you want to whitelist. For example: :email
What you're seeing is a security feature of newer versions of Rails. You will have to create a whitelist for the attributes which can be updated by the params as entered by the user. Otherwise, you will have to set each value manually.
Here's a sample of whitelisting certain params:
ActiveAdmin.register Post do
permit_params :title, :content, :publisher_id
end
See the ActiveAdmin docs on the subject:
https://github.com/gregbell/active_admin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters

How to make rack session cookies httponly?

I am using Ruby and Sinatra to develop an application.
I use
enable :sessions
in order to use the session variable provided by rack. How can I make all of the session cookies be HTTPOnly? Is it like this by default? I can't find any documentation on this.
Instead of enable :sessions:
use Rack::Session::Cookie, {:httponly => true }
I'd suggest using the encrypted_cookie gem instead, it's far more secure. As an example, here's what I'll probably have for a project:
# app/main.rb
module Example
class App < Sinatra::Base # this class in its own file
# stuff here
end
end
# app/config.rb
require "main"
module Example
def self.app #
Rack::Builder.app do
cookie_settings = {
:key => 'usr',
:path => "/",
:expire_after => 86400, # In seconds, 1 day.
:secret => ENV["COOKIE_KEY"], # load this into the environment of the server
:httponly => true
}
cookie_settings.merge!( :secure => true ) if ENV["RACK_ENV"] == "production"
# AES encryption of cookies
use Rack::Session::EncryptedCookie, cookie_settings
# other stuff here
run App
end
end
end
# config.ru
require "app/config"
run Example.app # this in the rackup file
(To clarify why I've laid it out this way - this kind of stucture allows me to split the app up and use it easier in tests by just requiring the app/config.rb. YMMV)

I can't get a backtrace in Rails 3

I'm trying to run the usual rails commands (rails s, rails g, rails c, etc) and I'm getting errors (because I'm migrating from MRI ruby and postgres to jruby and neo4j), which would be fine if only there was a stack trace.
It looks like this:
$ rails s
NameError: uninitialized constant Authorization::ActiveRecord
I'm expecting errors like this because Neo4j doesn't use ActiveRecord and it no longer exists, but I really need to see which file is calling ActiveRecord so I can fix this. But nothing I've found from google or tried in the code has brought the backtrace back to me. ;_;
My config/application.rb is:
require File.expand_path('../boot', __FILE__)
require 'action_controller/railtie'
require 'action_mailer/railtie'
require 'active_resource/railtie'
require 'rails/test_unit/railtie'
require 'sprockets/railtie'
require 'neo4j'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require *Rails.groups(:assets => %w(development test))
# If you want your assets lazily compiled in pro duction, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module MyApp
class Application < Rails::Application
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, chanmge this if you want to expire all your assets
config.assets.version = '1.1'
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# this was done to load all modules in lib
# following directions at: https://stackoverflow.com/questions/3356742/best-way-to-load-module-class-from-lib-folder-in-rails-3/3962321#3962321
config.autoload_paths += Dir["#{config.root}/lib/**/"]
#for rails-ckeditor
config.autoload_paths += %W( #{config.root}/app/models/ckeditor )
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
end
end
And my config/environments/development.rb is:
MyApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
#config.action_view.debug_rjs = true $ turn off for rails 3.1
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
#Devise wants this:
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
config.log_level = :debug
# Do not compress assets
config.assets.compress = false
# Expand the lines which load the assets
config.assets.debug = true
end
I'm not aware of any other files that might effect the logger/backtrace situation. I'd include more but this feels like such a general problem I'm really not sure what to include.
Update: I'm pretty sure this question is a duplicate of here (althought I'm trying to get it working in any environment).

Thin throws error: undefined method "call"

I'm having trouble getting thin to run my webapp. It starts up just fine, but whenever I make a request thin craps out and I get the following popping up in the log:
>> Listening on 0.0.0.0:3000, CTRL+C to stop
!! Unexpected error while processing request: undefined method `call'
for #<Rack::Request:0x7f104facb640>
This configuration worked just fine on my Debian server; I'm running Gentoo now.
This is my rackup file:
require 'toto'
# Rack config
use Rack::Static, :urls => ['/css', '/js', '/images', '/favicon.ico', '/pubkey.asc'], :root => 'public'
use Rack::Request
use Rack::CommonLogger
if ENV['RACK_ENV'] == 'development'
use Rack::ShowExceptions
end
#
# Create and configure a toto instance
#
toto = Toto::Server.new do
#
# Add your settings here
# set [:setting], [value]
#
set :author, "jibcage" # blog author
set :title, "Going to Grass" # site title
set :root, "index" # page to load on /
# set :date, lambda {|now| now.strftime("%d/%m/%Y") } # date format for articles
set :markdown, :smart
Delete the line
use Rack::Request

Resources