ChefSpec unable to find cookbook - ruby

When I run my unit test case (written in ChefSpec) I get the following error:
Chef::Exceptions::CookbookNotFound: Cookbook azuredns not found. If
you're loading azuredns from another cook book, make sure you
configure the dependency in your metadata
Following are my spec file, recipe file and metadata file
azuredns/spec/get_azure_token_spec.rb
require 'chefspec'
require 'rest-client'
describe 'azuredns::get_azure_token' do
let(:chef_run) do
# Step into the provider
runner = ChefSpec::SoloRunner.new(step_into: ['azuredns_token'])
# Read test data from a json file
file_path = File.expand_path('test_data.json', __dir__)
file = File.open(file_path)
contents = file.read
node_attr = JSON.parse(contents)
# Load test data into node object
runner.node.consume_attributes(node_attr)
runner.converge(described_recipe)
end
before(:each) do
# Mock post method of RestClient
allow(RestClient).to receive(:post)
.and_return({ access_token: 'i-am-a-token' }.to_json)
end
it 'retrieves token' do
expect(chef_run).to retrieve_azuredns_token('azure_token')
end
it 'varifies the expected value of azure_rest_token' do
expect(chef_run.node['azure_rest_token']).to eq('Bearer i-am-a-token')
end
it 'does not retrieve token due to incorrect resource name' do
expect(chef_run).to_not retrieve_azuredns_token('azure_token1')
end
it 'raises exception due to error in response' do
# Mock post method of RestClient
allow(RestClient).to receive(:post)
.and_return({ error: 'invalid_grant' }.to_json)
expect { chef_run }.to raise_error(Exception)
end
end
azuredns/recipe/get_azure_token.rb
require 'rest_client'
require 'json'
cloud_name = node['workorder']['cloud']['ciName']
cloud = node['workorder']['services']['dns'][cloud_name]
dns_attributes = cloud['ciAttributes']
# Establish connection and get a security token
token = azuredns_token 'azure_token' do
tenant_id dns_attributes['tenant_id']
client_id dns_attributes['client_id']
client_secret dns_attributes['client_secret']
end
token.run_action(:retrieve)
azuredns/metadata.rb
name 'Azuredns'
maintainer 'Shaffan'
maintainer_email 'shaffan.chaudhry1#gmail.com'
license 'Apache License, Version 2.0'
description 'Installs/Configures Azure DNS'
version '0.1.0'
depends 'azure'
Please help!

Azuredns != azuredns :-)
Fix the name in your metadata. Chef, and pretty much everything from the UNIX world, is case sensitive.

Related

Why is server.rb throwing this error in terminal

I am following along with this stripe tutorial but the server.rb in the example from Stripe's Github is throwing an error when I run Ruby server.rb
I am very new to ruby so I could be doing things wrong.
What I did was:
Installed Ruby, Rails, Stripe CLI, Sinatra, and dotenv
Downloaded the example from the site by typing Stripe samples create
developer-office-hours
cd'd into the server directory and ran ruby
server.rb
this is the error
1: from server.rb:10:in '<main.'
server.rb:10:in 'join': no implicit conversation of nil into string (TypeError)
here is the server.rb file
require 'stripe'
require 'sinatra'
require 'dotenv'
# Replace if using a different env file or config
Dotenv.load
Stripe.api_key = ENV['STRIPE_SECRET_KEY']
set :static, true
set :public_folder, File.join(File.dirname(__FILE__), ENV['STATIC_DIR'])
set :views, File.join(File.dirname(__FILE__), ENV['STATIC_DIR'])
set :port, 4242
get '/' do
content_type 'text/html'
send_file File.join(settings.public_folder, 'index.html')
end
post '/webhook' do
# You can use webhooks to receive information about asynchronous payment events.
# For more about our webhook events check out https://stripe.com/docs/webhooks.
webhook_secret = ENV['STRIPE_WEBHOOK_SECRET']
payload = request.body.read
if !webhook_secret.empty?
# Retrieve the event by verifying the signature using the raw body and secret if webhook signing is configured.
sig_header = request.env['HTTP_STRIPE_SIGNATURE']
event = nil
begin
event = Stripe::Webhook.construct_event(
payload, sig_header, webhook_secret
)
rescue JSON::ParserError => e
# Invalid payload
status 400
return
rescue Stripe::SignatureVerificationError => e
# Invalid signature
puts "⚠️ Webhook signature verification failed."
status 400
return
end
else
data = JSON.parse(payload, symbolize_names: true)
event = Stripe::Event.construct_from(data)
end
# Get the type of webhook event sent - used to check the status of PaymentIntents.
event_type = event['type']
data = event['data']
data_object = data['object']
if event_type == 'some.event'
puts "🔔 Webhook received!"
end
content_type 'application/json'
{
status: 'success'
}.to_json
end
stripe login
This is a crucial step.
stripe samples create adding-sales-tax
cd adding-sales-tax/server
bundle install
If you don't have bundler, gem install bundler
bundle exec ruby server.rb
Open http://localhost:4242

`initialize': No such file or directory # rb_sysopen when using Nokogiri to open site

I created a CLI program that uses Scraper class to scrape site. I am Using Nokogiri and Open-URI. The error on top is popping up. I looked online and did not find help.
I made sure the site doesn't have typos.
from the CLI class I create a new Scraper class using the site as arg
class KefotoScraper::CLI
attr_accessor :kefoto_scraper
def initialize
site = "https://www.kefotos.mx"
#kefoto_scraper = Scraper.new(site)
end
end
In Scraper I have the following code:
class Scraper
attr_accessor :doc, :product_names, :site, :name, :link
def initialize(site)
#site = site
#doc = doc
#product_names = product_names
#name = name
#link = link
#price_range = [].uniq
scrape_product
end
def get_html
#doc = Nokogiri::HTML(open(#site))
#product_names = doc.css(".navbar-nav li")
product_names
end
def scrape_product
get_html.each {|product|
#name = product.css("span").text
plink = product.css("a").attr("href").text
#link = "#{site}#{link}"
link_doc = Nokogiri::HTML(open(#link))
pr = link_doc.scan(/[\$£](\d{1,3}(,\d{3})*(\.\d*)?)/)
prices = pr_link.text
prices.each {|price|
if #price_range.include?(price[0]) == false
#price_range << price[0]
end
}
new_product = Products.new(#name, #price_range)
puts new_product
}
end
end
I get the following error:
scraper.rb:18:in `initialize': No such file or directory # rb_sysopen - https://www.kefotos.mx (Errno::ENOENT)
open by default operates on local files, not URLs. That error means "I can't find a file on your hard drive named https://www.kefotos.mx".
You can let it work on URIs by requiring the open-uri library:
require 'open-uri'
This will make your code work, but it is a much better practice to use a proper HTTP client to read HTTP resources, as an attacker could potentially use an overloaded open() to access files on your machine's hard drive.
For example, if you were to use just net/http:
# At the top of your scraper.rb:
require 'net/http'
# Then, in your class:
link_doc = Nokogiri::HTML(Net::HTTP.get(URI(#link)))

Mechanize (Ruby gem) not recognizing a form from a saved HTML file, but it recognizes the form when accessing the actual website?

I'm trying to write Rspec tests for my Mechanize agent.
My agent is supposed to go to a website, log into the form, then scrape some data off the website. I also downloaded FakeWeb to stub the HTTP requests, and make my tests faster.
Here is my account_spec.spec file:
require 'spec_helper'
describe Account do
before(:each) { #account = Account.new('bob', '1234') }
describe '#login' do
before(:each) do
home_page = File.read('spec/html/home_page.html')
login_page = File.read('spec/html/login_page.html')
FakeWeb.register_uri(:get,
"https://www.example.com/",
body: home_page,
status: ["200", "Success"],
content_type: "text/html")
FakeWeb.register_uri(:get,
"https://www.example.com/account/login",
body: login_page,
status: ["200", "Success"],
content_type: "text/html")
#web_crawler = Mechanize.new
#home_page = #web_crawler.get("https://www.example.com/")
#login_page = #web_crawler.get("https://www.example.com/account/login")
end # -- before :each
it 'finds the login form' do
login_form = #login_page.form_with(:class => "form login")
puts login_form.class # ==> nil:NilClass
end
end # -- #login
end # -- Account
However, when I comment out the FakeWeb uri for example/account/login (it then accesses the real server), it actually returns the correct form. Basically, if I am searching for the form in my locally saved HTML file, Mechanize can not find it, but if I check the actual website, it does find it. I would like to know if there is a way around this, and why this happens.
Any help would be greatly appreciated.

Apartment ruby gem : Want to Catch an exception

I am using this apartment a ruby gem.
I have add this in application.rb file:
config.middleware.use 'Apartment::Elevators::Subdomain'
When i try hit this in browser url 'test.domain.local:3000' where sub domain 'test' schema does not exist in PostgreSQL, i see this error
Apartment::SchemaNotFound (One of the following schema(s) is invalid: test, "public")
I know this is normal behavior of gem but want to catch this exception and redirect user to some other page, how can i do that?
This is what I did:
Create file under lib/rescued_apartment_middleware.rb
module RescuedApartmentMiddleware
def call(*args)
begin
super
rescue Apartment::TenantNotFound
Rails.logger.error "ERROR: Apartment Tenant not found: #{Apartment::Tenant.current.inspect}"
return [404, {"Content-Type" => "text/html"}, ["#{File.read(Rails.root.to_s + '/public/404.html')}"] ]
end
end
end
and add to your Apartment initializer file following lines:
require 'rescued_apartment_middleware'
Rails.application.config.middleware.use 'Apartment::Elevators::Subdomain'
Apartment::Elevators::Subdomain.prepend RescuedApartmentMiddleware
This works like a charm! (Tested with ruby 2.1 and Rails 4.1)

How would I use VCR (with WebMock) in this scenario?

I'm developing a DSL for building API wrappers, named Hendrix. I am having problems with the testing of the DSL. As it is a API wrapper, it needs to interact with external services. I am not sure how to approach this in terms of testing. I'm using RSpec and tried configuring VCR with WebMock, but no luck. How am I supposed to test this particular scenario if I don't have direct access to what request is being made?
This is my spec_helper.rb:
$VERBOSE = nil
require 'simplecov'
require 'coveralls'
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
]
SimpleCov.start { add_filter '/spec/' }
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'hendrix'
require 'vcr'
VCR.configure do |c|
c.cassette_library_dir = 'spec/cassettes'
c.hook_into :webmock
end
RSpec.configure do |config|
config.treat_symbols_as_metadata_keys_with_true_values = true
config.run_all_when_everything_filtered = true
config.filter_run :focus
config.order = 'random'
config.extend VCR::RSpec::Macros
end
The project is in its early stages (working towards version 0.1.0 at the moment). The syntax of the DSL is as follows:
require 'hendrix'
Hendrix.build 'Jimi' do
base 'https://api.github.com'
client :issues do
action :issue, '/repos/:owner/:repo/issues/:number'
end
end
Jimi.issue('rafalchmiel', 'hendrix', 1)
# => {"url"=>"https://api.github.com/repos/rafalchmiel/hendrix/issues/1",
# "labels_url"=> ...
Jimi.issue('rafalchmiel', 'hendrix', 1).title
# => "Implement parameters in actions"
In most specs, I'm testing what the methods from the master module (in this case Jimi.issue etc) return and whether it is in a Hashie::Mash format. How would I test this? I don't know where to start.
For integration tests, I usually stub the endpoint with webmock directly, without trying to record an actual request. This means you can control the response and the expectation in the same place. You can place expectations on whether your library parses the response correctly and you can write tests that verify that the request has been made correctly. Go through each of the features of your gem to get a list of features. Here's an example:
require "webmock/rspec"
describe "parsing results" do
let(:url) { "http://..." }
it "parses results into nice methods" do
stub_request(:get, url)
.to_return(
body: { title: "implement" }.to_json,
headers: { content_type: "application/json" },
)
perform_request
expect(response.title).to eq "implement"
end
it "sends the user agent header correctly" do
stub_request(:get, url)
perform_request
expect(a_request(:get, url).with(
headers: { user_agent: "hendrix" }
)).to have_been_made.once
end
it "interpolates values in URLs"
it "supports DELETE requests"
it "supports HTTP Basic"
def perform_request
# ...
end
end
Try not to record real requests: it's hard to control the right circumstances with real web servers, especially if you're not the one who wrote the specs. Especially when you write a general purpose library like this. VCR is nice if you want to access one particular server and your code really depends on that one server.
Also don't check on types. I see that quite a lot in your gem right now. Nobody cares if you return a Hashie::Mash object. As my first spec shows, you just want to be able to access the attributes cleanly.

Resources