Not able access data in "it" rails rspec test class - ruby

When we are trying to execute the below code we are not able access data newAccount and also not able to search date in active records in it method
Code Extract:
describe "search with name" do
before :each do
newAccount = Account.new
newAccount.firstname = "涯噘暮"
newAccount.id = "405"
newAccount.save
data = Account.execute_sql(['Select * from account where sfid= ? ','1'])
puts "Debug : #{data.to_json}"
newAccount = Account.new
newAccount.firstname = "涯 噘 暮"
newAccount.id = "2"
newAccount.save
end
it "should return direct matches during search" do
puts "#{newAccount}"
puts "#{Account.find_by_id(405)}"
end
end
Details of gem lib: These are the libraries that we are using for testing.
gem 'rspec-rails', '2.5.0'
gem 'faker'
gem 'capybara'
gem 'guard-rspec'
gem 'launchy'
gem 'simplecov', :require => false
gem 'resque_spec'

You have 2 errors here:
Variable names in Ruby are case-sensitive, so newaccount is different from newAccount, use one of them, preferably Ruby style guide recommends snake case (new_account)
newAccount in before(:each) is not visible in any it block. Consider them as different methods of one object, this way each method has its own local variables, that are invisible for other variables. The solution is to use instance variables, that can be shared inside different methods of one object.
This code should work:
describe "search with name" do
before :each do
#newAccount = Account.new
#newAccount.firstname = "涯噘暮"
#newAccount.id = "405"
#newAccount.save
data = Account.execute_sql(['Select * from account where sfid= ? ','1'])
puts "Debug : #{data.to_json}"
#newAccount = Account.new
#newAccount.firstname = "涯 噘 暮"
#newAccount.id = "2"
#newAccount.save
end
it "should return direct matches during search" do
puts "#{#newAccount}"
puts "#{Account.find_by_id(405)}"
end
end
You need to check if your account is really saved. You can
Add p #newAccount.errors.full_messages after #newAccount.save to see if there are any validation errors preventing your model to be saved.
Use #newAccount.save! instead of #newAccount.save (note the ! character). This will throw an exception if your save was unsuccessful.

Related

Ruby gem - How do I test my own ruby gem via IRB?

Okay so I am completely new to using IRB so I have no idea what I am doing wrong.
Here is my gem that I built
# frozen_string_literal: true
require_relative "badwordgem/version"
require 'yaml' #this will need to use the badlist.yml file
module Badwordgem
class Error < StandardError; end
class Base
class << self # assign class to itself so self does not need to be used for every method
def badlist
#badlist ||= YAML.load_file(File.expand_path("badlist.yml", __dir__)) # This will load in the bad words from our YML file and it will assign it to the badlist variable
end
def sanitize(input = "sassy") # method to take in user input to check for profanity
word = input.downcase # It will change the user input and set it to lowercase to match our bad list of words
badlist.each do |key, value| # For every word in the badlist assign it a key(a bad word), and a value(then replace the bad work with * symbol)
word.gsub!(/\b#{key}\b/, value) # For each word the user has inputed replace the old word(key) with the new word(value)
end
word # return the word whether it contains profanity or not
end
end
end
end
Essentially it tests to see if a word is bad or not based on my list of badwords.
I have installed and built it but I have no idea how to test it in IRB.
I've tried running badwordgem.sanitize(hello) etc. but that clearly is wrong as it gives me this error undefined local variable or method badwordgem' for main:Object'
What command in IRB do I type to test it??

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

'Error: Cannot open "/home/<...>/billy-bones/=" for reading' while using pry and DataMapper

So, I'm trying to build a quick console program for my development needs, akin to rails console (I'm using Sinatra + DataMapper + pry).
I run it and launch cat = Category.new(name: 'TestCat', type: :referential). It gives me the following error:
Error: Cannot open "/home/art-solopov/Projects/by-language/Ruby/billy-bones/=" for reading.
What could be the cause of the problem?
console:
#!/usr/bin/env ruby
$LOAD_PATH << 'lib'
require 'pry'
require 'config'
binding.pry
lib/config.rb:
# Configuration files and app-wide requires go here
require 'sinatra'
require 'data_mapper'
require 'model/bill'
require 'model/category'
configure :production do
DataMapper::Logger.new('db-log', :debug)
DataMapper.setup(:default,
'postgres://billy-bones:billy#localhost/billy-bones')
DataMapper.finalize
end
configure :development do
DataMapper::Logger.new($stderr, :debug)
DataMapper.setup(:default,
'postgres://billy-bones:billy#localhost/billy-bones-dev')
DataMapper.finalize
DataMapper.auto_upgrade!
end
configure :test do
require 'dm_migrations'
DataMapper::Logger.new($stderr, :debug)
DataMapper.setup(:default,
'postgres://billy-bones:billy#localhost/billy-bones-test')
DataMapper.finalize
DataMapper.auto_migrate!
end
lib/model/category.rb:
require 'data_mapper'
class Category
include DataMapper::Resource
property :id, Serial
property :name, String
property :type, Enum[:referential, :predefined, :computable]
has n, :bills
# has n, :tariffs TODO uncomment when tariff ready
def create_bill(params)
# A bill factory for current category type
case type
when :referential
ReferentialBill.new params
when :predefined
PredefinedBill.new params
when :computable
ComputableBill.new params
end
end
end
If I substitute pry with irb in the console script, it goes fine.
Thank you very much!
P. S.
Okay, yesterday I tried this script again, and it worked perfectly. I didn't change anything. I'm not sure whether I should remove the question now or not.
P. P. S.
Or actually not... Today I've encountered it again. Still completely oblivious to what could cause it.
** SOLVED **
DAMN YOU PRY!
Okay, so here's the difference.
When I tested it the second time, I actually entered a = Category.new(name: 'TestCat', type: :referential) and it worked. Looks like pry just thinks cat is a Unix command, not a valid variable name.
Not answer to the pry question I just generally hate case statements in ruby.
Why not change:
def create_bill(params)
# A bill factory for current category type
case type
when :referential
ReferentialBill.new params
when :predefined
PredefinedBill.new params
when :computable
ComputableBill.new params
end
end
to:
def create_bill(params)
# A bill factory for current category type
self.send("new_#{type}_bill",params)
end
def new_referential_bill(params)
ReferentialBill.new params
end
def new_predefined_bill(params)
PredefinedBill.new params
end
def new_computable_bill(params)
ComputableBill.new params
end
You could make this more dynamic but I think that would take away from readability in this case but if you'd like in rails this should do the trick
def create_bill(params)
if [:referential, :predefined, :computable].include?(type)
"#{type}_bill".classify.constantize.new(params)
else
#Some Kind of Handling for non Defined Bill Types
end
end
Or this will work inside or outside rails
def create_bill(params)
if [:referential, :predefined, :computable].include?(type)
Object.const_get("#{type.to_s.capitalize}Bill").new(params)
else
#Some Kind of Handling for non Defined Bill Types
end
end

Model not being saved using Selenium but saved using Rack::Test

I have the following test that works in Rack::Test but not using Selenium. I.e. if I add , js: true to the describe block, I get an error message in Firefox saying that it couldn't find the License with id=(the id of #l)
describe "should hide allocation rule # for pdf & clickthrough licenses" do
it "reads current state and shows/hides fields appropriately" do
#l = FactoryGirl.create(:license:,
way: License::CLICK_WAY)
visit edit_admin_license_path(#l)
end
end
Why? I must be missing something. I can verify with Sequel Pro that the record is not getting saved when using js: true.
I need this spec to run in Selenium because I have javascript to test.
The simple solution was to turn transactional fixtures off.
Why does my Cucumber test fail when run with Selenium?
in spec/spec_helper.rb:
RSpec.configure do |config|
config.use_transactional_fixtures = false
config.before :each do
if Capybara.current_driver == :rack_test
DatabaseCleaner.strategy = :transaction
else
DatabaseCleaner.strategy = :truncation
end
DatabaseCleaner.start
end
config.after do
DatabaseCleaner.clean
end
end
and in the Gemfile, test section
gem 'database_cleaner'

With Test::Unit, how can I run a bit of code before all tests (but not each test)?

In my test app, which uses test::unit, I need to start by pulling a bunch of data from various sources. I'd like to only do this once - the data is only read, not written, and doesn't change between tests, and the loading (and error checking for the loading), takes some time.
There are values that I DO want reset every time, and those are easy enough, but what if I want persistant accessible values? What's the best way to do this?
I'm especially interested in solutions that would let my push those assignments to some module that can be included in all my tests, since they all need access to this data.
Why do you need it inside the test? You could define it gloabl:
gem 'test-unit'#, '>= 2.1.1' #startup
require 'test/unit'
GLOBAL_DATA = 11
class My_Tests < Test::Unit::TestCase
def test_1()
puts "Testing startup 1"
assert_equal(11, GLOBAL_DATA)
end
end
GLOBAL_DATA could be a (singleton)-class (respective an instance).
If you have only one testclass, you may use TestCase.startup:
gem 'test-unit'#, '>= 2.1.1' #startup
require 'test/unit'
class My_Tests < Test::Unit::TestCase
def self.startup
puts "Define global_data "
##global_data = 11
end
def test_1()
puts "Testing 1"
assert_equal(11, ##global_data = 11)
end
def test_2()
puts "Testing 2"
assert_equal(11, ##global_data = 11)
end
end
You can just put them at the top of the class. They will get executed, and then your tests will get executed.
You could do this in the setup method:
def setup
if !defined?(##initial_data)
# Whatever you need to do to get your initial data
##initial_data = foo
end
#other_data = bar
end

Resources