check proxy and get timout with ruby-on-rails - ruby-on-rails

I have ruby on rails 4.
How I can to check proxy and get information abot this proxy (timeout and etc.), if it work?
I parse page with nokoriri through proxy.
page = Nokogiri::HTML(open("http://bagche.ru/home/radio_streem/", :proxy => "http://213.135.96.35:3129", :read_timeout=>10))

gem install curb
require 'net/http'
require 'net/ping'
require 'curb'
def proxy_check
#proxies = Proxy.all
url = "ya.ru"
#proxies.each do |p|
proxy = Net::Ping::TCP.new(p.proxy_address, p.proxy_port.to_i)
if proxy.ping?
#resp = Curl::Easy.new(url) { |easy|
easy.proxy_url = p.proxy_address
easy.proxy_port=p.proxy_port.to_i
# easy.timeout=90
# easy.connect_timeout=30
easy.follow_location = true
easy.proxy_tunnel = true
}
begin
#resp.perform
#resp.response_code
rescue
puts "CURL_GET -e- fail "+p.proxy_address
if #resp.response_code == 200
p.proxy_status = 1
p.proxy_timeout = #resp.total_time
else
p.proxy_status = 0
puts "CURL_GET fail "+p.proxy_address
end
end
else
p.proxy_status = 0
puts "ping fail "+p.proxy_address
end
p.save
end
end
returned 200 if availabil.

Related

Upload large file to S3 from direct url aws-sdk in Ruby on Rails

In my app I currently support upload from a direct download url, either the user inputs a url, or one is generated from a Box file picker widget. I do this with a Net:HTTP request, writing each segment as it comes to a filesystem.
Now I want to change to storing files from url in S3, for files too big to put in memory.
Below is a snippet I am currently working on:
queue = Queue.new
up_url = presigned_url_from_aws
down_uri = remote_download_url
producer = Thread.new do
# stream the file from the url,
# (code based on something currently working)
Net::HTTP.start(down_uri.host, down_uri.port, :use_ssl => (down_uri.scheme == 'https')) {|http|
http.request_get(down_uri.path) {|res|
res.read_body {|seg|
queue << seg
update_progress()
}
}
}
end
consumer = Thread.new do
# turn queue input into body_stream ?
end
# Use presigned url to upload file to aws
Net::HTTP.start(up_url.host) do |http|
http.send_request("PUT", up_url.request_uri, body_stream, {
# This is required, or Net::HTTP will add a default unsigned content-type.
"content-type" => "",
})
end
I eventually found a solution that worked. As before, this code is in a ProgressJob class. I used the aws multipart upload api. I created a queue for segments, a producer thread to put segments into the queue, a consumer thread to take segments out of the queue for further processing, and a thread to close the queue at the right time. In the consumer thread, I put the segments into a StringIO object until it each but the last was least 5 MB (minimum size for upload part), and sent the parts to s3 as I got them, to not fill up disk or memory. There were a lot of gotchas, but below is the working code I ended up with, in case this helps someone else:
require 'tempfile'
require 'open-uri'
require 'fileutils'
require 'net/http'
require 'aws-sdk-s3'
class CreateDatafileFromRemoteJob < ProgressJob::Base
Thread.abort_on_exception=true
FIVE_MB = 1024 * 1024 * 5
def initialize(dataset_id, datafile, remote_url, filename, filesize)
#remote_url = remote_url
#dataset_id = dataset_id
#datafile = datafile
#filename = filename
#filesize = filesize #string because it is used in display
if filesize.to_f < 4000
progress_max = 2
else
progress_max = (filesize.to_f / 4000).to_i + 1
end
super progress_max: progress_max
end
def perform
more_segs_to_do = true
upload_incomplete = true
#datafile.binary_name = #filename
#datafile.storage_root = Application.storage_manager.draft_root.name
#datafile.storage_key = File.join(#datafile.web_id, #filename)
#datafile.binary_size = #filesize
#datafile.save!
if IDB_CONFIG[:aws][:s3_mode]
upload_key = #datafile.storage_key
upload_bucket = Application.storage_manager.draft_root.bucket
if Application.storage_manager.draft_root.prefix
upload_key = "#{Application.storage_manager.draft_root.prefix}#{#datafile.storage_key}"
end
client = Application.aws_client
if #filesize.to_f < FIVE_MB
web_contents = open(#remote_url) {|f| f.read}
Application.storage_manager.draft_root.copy_io_to(#datafile.storage_key, web_contents, nil, #filesize.to_f)
upload_incomplete = false
else
parts = []
seg_queue = Queue.new
mutex = Mutex.new
segs_complete = false
segs_todo = 0
segs_done = 0
begin
upload_id = aws_mulitpart_start(client, upload_bucket, upload_key)
seg_producer = Thread.new do
uri = URI.parse(#remote_url)
Net::HTTP.start(uri.host, uri.port, :use_ssl => (uri.scheme == 'https')) {|http|
http.request_get(uri.path) {|res|
res.read_body {|seg|
mutex.synchronize {
segs_todo = segs_todo + 1
}
seg_queue << seg
update_progress
}
}
}
mutex.synchronize {
segs_complete = true
}
end
seg_consumer = Thread.new do
part_number = 1
partio = StringIO.new("", 'wb+')
while seg = seg_queue.deq # wait for queue to be closed in controller thread
partio << seg
if partio.size > FIVE_MB
partio.rewind
mutex.synchronize {
etag = aws_upload_part(client, partio, upload_bucket, upload_key, part_number, upload_id)
parts_hash = {etag: etag, part_number: part_number}
parts.push(parts_hash)
}
part_number = part_number + 1
partio.close if partio&.closed?
partio = StringIO.new("", 'wb+')
end
mutex.synchronize {
segs_done = segs_done + 1
}
end
# upload last part, less than 5 MB
mutex.synchronize {
partio.rewind
etag = aws_upload_part(client, partio, upload_bucket, upload_key, part_number, upload_id)
parts_hash = {etag: etag, part_number: part_number}
parts.push(parts_hash)
Rails.logger.warn("Another part bites the dust: #{part_number}")
partio.close if partio&.closed?
aws_complete_upload(client, upload_bucket, upload_key, parts, upload_id)
upload_incomplete = false
}
end
controller = Thread.new do
while more_segs_to_do
sleep 0.9
mutex.synchronize {
if segs_complete && ( segs_done == segs_todo)
more_segs_to_do = false
end
}
end
seg_queue.close
end
rescue Exception => ex
# ..|..
#
Rails.logger.warn("something went wrong during multipart upload")
Rails.logger.warn(ex.class)
Rails.logger.warn(ex.message)
ex.backtrace.each do |line|
Rails.logger.warn(line)
end
Application.aws_client.abort_multipart_upload({
bucket: upload_bucket,
key: upload_key,
upload_id: upload_id,
})
raise ex
end
end
else
filepath = "#{Application.storage_manager.draft_root.path}/#{#datafile.storage_key}"
dir_name = File.dirname(filepath)
FileUtils.mkdir_p(dir_name) unless File.directory?(dir_name)
File.open(filepath, 'wb+') do |outfile|
uri = URI.parse(#remote_url)
Net::HTTP.start(uri.host, uri.port, :use_ssl => (uri.scheme == 'https')) {|http|
http.request_get(uri.path) {|res|
res.read_body {|seg|
outfile << seg
update_progress
}
}
}
end
upload_incomplete = false
end
while upload_incomplete
sleep 1.3
end
end
def aws_mulitpart_start(client, upload_bucket, upload_key)
start_response = client.create_multipart_upload({
bucket: upload_bucket,
key: upload_key,
})
start_response.upload_id
end
def aws_upload_part(client, partio, upload_bucket, upload_key, part_number, upload_id)
part_response = client.upload_part({
body: partio,
bucket: upload_bucket,
key: upload_key,
part_number: part_number,
upload_id: upload_id,
})
part_response.etag
end
def aws_complete_upload(client, upload_bucket, upload_key, parts, upload_id)
response = client.complete_multipart_upload({
bucket: upload_bucket,
key: upload_key,
multipart_upload: {parts: parts, },
upload_id: upload_id,
})
end
end

Why are my scripts from lib/assets directory in a Rails application not executing, or erring out?

I'm trying to use ConnectWise API's in my Rails 3 application. I've built and tested an API using plain ruby and it's successful. Now I'm trying to add this script into lib/assets in my Rails app to run but It seems to be either not executing the script, or executing and failing without giving me any error output.
Here are the successful Ruby scripts:
CompanyApis Class:
require 'builder'
class CompanyApis
def self.get_company
cw_company_id = 21920
integrator_company_id = 'COMPANY_ID'
integrator_login_id = 'INTERGRATOR_LOGIN'
integrator_password = 'INTEGRATOR PW'
xml = Builder::XmlMarkup.new(:indent=>2)
xml.instruct!
xml.tag!('soap:Envelope',
:'xmlns:soap' => 'http://schemas.xmlsoap.org/soap/envelope/',
:xmlns => 'http://connectwise.com'){
xml.tag!('soap:Body'){
xml.tag!('GetCompany'){
xml.tag!('credentials'){
xml.CompanyId(integrator_company_id)
xml.IntegratorLoginId(integrator_login_id)
xml.IntegratorPassword(integrator_password)
}
xml.id(cw_company_id)
}
}
}
end
end
CwIntegrator Class:
require 'net/https'
require 'uri'
require 'nokogiri'
require './company_api'
class CwIntegrator
cw_company_id = 21920
cw_hostname = 'cw.host.com'
companyapi_url = "https://#{cw_hostname}/v4_6_release/apis/2.0/CompanyApi.asmx"
uri = URI.parse(companyapi_url)
# Use for proxying to Kali
#proxy_addr = '172.16.1.149'
#proxy_port = 8080
request = Net::HTTP::Post.new(uri.path)
request.add_field('Content-Type', 'text/xml; charset=utf-8')
request.add_field('SOAPAction', 'http://connectwise.com/GetCompany')
request.body = CompanyApis.get_company
http = Net::HTTP.new(uri.host, uri.port)
# Use for proxying to Kali
#http = Net::HTTP.new(uri.host, uri.port, proxy_addr, proxy_port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
response = http.start {|h| h.request(request)}
company_info = []
xml_doc = Nokogiri::XML(response.body).remove_namespaces!
company_name = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/CompanyName').text
company_street_addr = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/StreetLines/string')[0].text
begin
company_street_addr2 = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/StreetLines/string')[1].text
end
company_city = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/City').text
company_state = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/State').text
company_zip = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/Zip').text
company_country = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/Country').text
company_status = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/Status').text
company_phone = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/PhoneNumber').text
company_fax = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/FaxNumber').text
company_www = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/WebSite').text
company_info += [company_name: company_name, cw_company_id: cw_company_id, company_name: company_name,
company_street_addr: company_street_addr, company_street_addr2: company_street_addr2,
company_city: company_city, company_state: company_state, company_zip: company_zip,
company_country:company_country,company_status: company_status, company_phone: company_phone,
company_fax: company_fax, company_www: company_www]
puts(company_info)
end
Running this script has this output:
ruby cw_integrator.rb
{:company_name=>"Orlando Fake Co, LLC.", :cw_company_id=>21920, :company_street_addr=>"STREET ADDR.", :company_street_addr2=>"Suite 400", :company_city=>"Orlando", :company_state=>"FL", :company_zip=>"32839", :company_country=>"United States", :company_status=>"Active Gold TTS", :company_phone=>"5558765309", :company_fax=>"", :company_www=>"www.myweb.com"}
So to add this to the Rails app I've added two .rb files to lib/assets, cw_apis.rb and cw_get_company_integrator.rb. Here are their contents:
CwApis class:
#!/usr/bin/env ruby
require 'builder'
class CwApis
def self.get_company_xml_request
cw_integrator_account = CwIntegratorAccount.first
integrator_company_id = cw_integrator_account.integrator_company_id
integrator_login_id = cw_integrator_account.integrator_login_id
integrator_password = cw_integrator_account.integrator_password
xml = Builder::XmlMarkup.new(:indent=>2)
xml.instruct!
xml.tag!('soap:Envelope',
:'xmlns:soap' => 'http://schemas.xmlsoap.org/soap/envelope/',
:xmlns => 'http://connectwise.com'){
xml.tag!('soap:Body'){
xml.tag!('GetCompany'){
xml.tag!('credentials'){
xml.CompanyId(integrator_company_id)
xml.IntegratorLoginId(integrator_login_id)
xml.IntegratorPassword(integrator_password)
}
xml.id(cw_integrator_account.cw_company_id)
}
}
}
end
end
And CwGetCompanyIntegrator Class:
#!/usr/bin/env ruby
require 'net/https'
require 'uri'
require 'nokogiri'
require 'assets/cw_apis'
class CwGetCompanyIntegrator
cw_integrator_account = CwIntegratorAccount.first
cw_hostname = cw_integrator_account.cw_hostname
company_api_url = "https://#{cw_hostname}/v4_6_release/apis/2.0/CompanyApi.asmx"
uri = URI.parse(company_api_url)
request = Net::HTTP::Post.new(uri.path)
request.add_field('Content-Type', 'text/xml; charset=utf-8')
request.add_field('SOAPAction', 'http://connectwise.com/GetCompany')
request.body = CwApis.get_company_xml_request
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL
response = http.start {|h| h.request(request)}
xml_doc = Nokogiri::XML(response.body).remove_namespaces!
company_name = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/CompanyName').text
company_street_addr = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/StreetLines/string')[0].text
begin
company_street_addr2 = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/StreetLines/string')[1].text
end
company_city = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/City').text
company_state = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/State').text
company_zip = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/Zip').text
company_country = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/Country').text
company_status = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/Status').text
company_phone = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/PhoneNumber').text
company_fax = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/FaxNumber').text
company_www = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/WebSite').text
CompanyInfosController.create!(cw_company_id: cw_integrator_account.cw_company_id, company_name: company_name,
company_street_addr: company_street_addr, company_street_addr2: company_street_addr2,
company_city: company_city, company_state: company_state, company_zip: company_zip,
company_country:company_country, company_status: company_status, company_phone: company_phone,
company_fax: company_fax, company_www: company_www)
end
I'm trying to execute the CwGetCompanyIntegrator class in my CwIntegratorAccountsController.
Here is the code inside the create action from the CwIntegratorAccountsController I've omitted index, show, new, edit, update, and destroy:
require 'assets/cw_get_company_integrator'
class CwIntegratorAccountsController < ApplicationController
skip_before_filter :require_company, :only => [:create,:new]
# GET /cw_integrator_accounts
# GET /cw_integrator_accounts.json
def create
unless CwIntegratorAccount.count >= 1
#cw_integrator_account = CwIntegratorAccount.new(params[:cw_integrator_account])
respond_to do |format|
if #cw_integrator_account.save
# Run the CW Integrator
CwGetCompanyIntegrator
format.html { redirect_to root_url, notice: 'cw_integrator success' }
#format.json { render json: #cw_integrator_account, status: :created, location: #cw_integrator_account }
else
format.html { render action: 'new' }
format.json { render json: #cw_integrator_account.errors, status: :unprocessable_entity }
end
end
end
end
end
I know that I'm getting past the if #cw_integrator_account.save, and CwGetCompanyIntegrator because I'm getting the redirect (and see it in the logs) from format.html { redirect_to root_url, notice: 'cw_integrator success' }, but the CwGetCompanyIntegrator is not erring or executing (properly any way).
What is the proper way to make this class execute?
lib is not autoloaded by default. You need to add it to the autoload path - see Auto-loading lib files in Rails 4
In addition, lib/assets is used by the Asset Pipeline. You should create a different folder for your classes.
Your code in CwGetCompanyIntegrator needs to be wrapped in a method, like the following block which you'd call using CwGetCompanyIntegrator.call
class CwGetCompanyIntegrator
def self.call
# execute code here
end
end

twitter update_with_media and carrierwave

I am trying to post updates from heroku using carrierwave to twitter... with media.
http://rdoc.info/gems/twitter/Twitter/API/Tweets#update_with_media-instance_method
I can do it without media, but when I try media, I keep running into problems.
Twitter.update_with_media("message", File.new(picture.picture_url.to_s))
I get the error:
Errno::ENOENT (No such file or directory - https://amazonlinktopicture)
Any ideas? I tried with File.open also and it didn't work.
Just for benefit of other
> Source
require 'twitter'
require 'open-uri'
config = YAML.load_file('twitter.yml')
Twitter.configure do |c|
c.consumer_key = config['consumer_key']
c.consumer_secret = config['consumer_secret']
c.oauth_token = config['oauth_token']
c.oauth_token_secret = config['oauth_token_secret']
end
# Tempfile
begin
uri = URI.parse('https://dev.twitter.com/sites/default/files/images_terms/tweet-display-guidelines-20110405.png')
media = uri.open
media.instance_eval("def original_filename; '#{File.basename(uri.path)}'; end")
p Twitter.update_with_media(Time.now.to_s, media)
rescue => e
p e
end
# StringIO
begin
uri = URI.parse('http://a3.twimg.com/a/1315421129/images/logos/twitter_newbird_blue.png')
media = uri.open
media.instance_eval("def original_filename; '#{File.basename(uri.path)}'; end")
p Twitter.update_with_media(Time.now.to_s, media)
rescue => e
p e
end
require 'open-uri'
Twitter.update_with_media("message", open(picture.picture_url.to_s) {|f| f.read })
begin
twitter_client = Twitter::REST::Client.new do |c|
c.consumer_key = config['consumer_key']
c.consumer_secret = config['consumer_secret']
c.oauth_token = config['oauth_token']
c.oauth_token_secret = config['oauth_token_secret']
end
twitter_client.update_with_media(message, open(picture.picture_url))
rescue Exception => exc
#message = exc.message
end
begin
twitter_client = Twitter::REST::Client.new do |client|
client.consumer_key = config['consumer_key']
client.consumer_secret = config['consumer_secret']
client.oauth_token = config['oauth_token']
client.oauth_token_secret = config['oauth_token_secret']
end
twitter_client.update_with_media(message, open(picture.picture_url))
rescue Exception => exc
#message = exc.message
end

Gem Resque Error - Undefined "method perform" after Overriding it form the super class

First of all Thanks for you all for helping programmers like me with your valuable inputs in solving day to day issues.
This is my first question in stack overflow as I am experiencing this problems from almost one week.
WE are building a crawler which crawls the specific websites and extract the contents from it, we are using mechanize to acheive this , as it was taking loads of time we decided to run the crawling process as a background task using resque with redis gem , but while sending the process to background I am experiencing the error as the title saying,
my code in lib/parsers/home.rb
require 'resque'
require File.dirname(__FILE__)+"/../index"
class Home < Index
Resque.enqueue(Index , :page )
def self.perform(page)
super (page)
search_form = page.form_with :name=>"frmAgent"
resuts_page = search_form.submit
total_entries = resuts_page.parser.xpath('//*[#id="PagingTable"]/tr[2]/td[2]').text
if total_entries =~ /(\d+)\s*$/
total_entries = $1
else
total_entries = "unknown"
end
start_res_idx = 1
while true
puts "Found #{total_entries} entries"
detail_links = resuts_page.parser.xpath('//*[#id="MainTable"]/tr/td/a')
detail_links.each do |d_link|
if d_link.attribute("class")
next
else
data_page = #agent.get d_link.attribute("href")
fields = get_fields_from_page data_page
save_result_page page.uri.to_s, fields
#break
end
end
site_done
rescue Exception => e
puts "error: #{e}"
end
end
and the superclass in lib/index.rb is
require 'resque'
require 'mechanize'
require 'mechanize/form'
class Index
#queue = :Index_queue
def initialize(site)
#site = site
#agent = Mechanize.new
#agent.user_agent = Mechanize::AGENT_ALIASES['Windows Mozilla']
#agent.follow_meta_refresh = true
#rows_parsed = 0
#rows_total = 0
rescue Exception => e
log "Unable to login: #{e.message}"
end
def run
log "Parsing..."
url = "unknown"
if #site.url
url = #site.url
log "Opening #{url} as a data page"
#page = #agent.get(url)
#perform method should be override in subclasses
#data = self.perform(#page)
else
#some sites do not have "datapage" URL
#for example after login you're already on your very own datapage
#this is to be addressed in 'perform' method of subclass
#data = self.perform(nil)
end
rescue Exception=>e
puts "Failed to parse URL '#{url}', exception=>"+e.message
set_site_status("error "+e.message)
end
#overriding method
def self.perform(page)
end
def save_result_page(url, result_params)
result = Result.find_by_sql(["select * from results where site_id = ? AND ref_code = ?", #site.id, utf8(result_params[:ref_code])]).first
if result.nil?
result_params[:site_id] = #site.id
result_params[:time_crawled] = DateTime.now().strftime "%Y-%m-%d %H:%M:%S"
result_params[:link] = url
result = Result.create result_params
else
result.result_fields.each do |f|
f.delete
end
result.link = url
result.time_crawled = DateTime.now().strftime "%Y-%m-%d %H:%M:%S"
result.html = result_params[:html]
fields = []
result_params[:result_fields_attributes].each do |f|
fields.push ResultField.new(f)
end
result.result_fields = fields
result.save
end
#rows_parsed +=1
msg = "Saved #{#rows_parsed}"
msg +=" of #{#rows_total}" if #rows_total.to_i > 0
log msg
return result
end
end
What's Wrong with this code?
Thanks

ActionMailer::Base.deliveries array not being populated

I'm trying to run an rspec test.
You can see most of that code here.
Maybe it's relevant: CoRegEmailWorker.perform contains this:
ProvisionalUser.where("unsubscribed = false AND disabled = false AND (email_sent_count < ? OR email_sent_count is NULL) AND (last_email_sent <= ? OR last_email_sent IS NULL) AND sign_up_date IS NULL",
ProvisionalUser::EMAIL_COUNT_LIMIT, email_sending_interval.hours.ago).
each{ |user|
begin
user.send_email
rescue Exception => ex
logger.error ex
end
}
and ProvisionalUser has this method:
def send_email
self.email_sent_count = self.email_sent_count.nil? ? 1 : self.email_sent_count + 1
self.last_email_sent = DateTime.now
self.disabled = true if self.email_sent_count == EMAIL_COUNT_LIMIT
self.save!
ProvisionalUserNotifier.send_registration_invite(self.id).deliver
end
Finally, ProvisionalUserNotifier inherits from MailGunNotifier which inherits from ActionMailer.
The problem I'm having is that the deliveries array is not being populated. In my `config/environments/test.rb'. I have this:
config.action_mailer.perform_deliveries = true
config.action_mailer.delivery_method = :test
I'm not certain what else is needed here.
i've even gone so far as to try this:
require "spec_helper"
require "action_mailer"
describe "unsubscribe functionality" do
pu1 = ProvisionalUser.new
pu1.email = 'contact_me#test.com'
pu1.partner = 'partner'
pu1.first_name = 'joe'
pu1.save!
before(:each) do
ActionMailer::Base.delivery_method = :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries = []
end
it "should send emails to subscribed users only" do
unsubscribed_user = FactoryGirl.build(:unsubscribed_user)
unsubscribed_user.save!
subscribed_user = FactoryGirl.create(:subscribed_user)
CoRegEmailWorker.perform
ActionMailer::Base.deliveries.length.should == 1
ActionMailer::Base.deliveries.first.email.should =~ subscribed_user.email
#sent.first.email.should_not =~ unsubscribed_user.email
#sent.first.email.should =~ subscribed_user.email
end
def sent
ActionMailer::Base.deliveries
end
end
wow. that was really annoying. because the exception was being eaten, i wasn't seeing that I was missing a neccessary value for the subject of the email to work.

Resources