Say I have the following spec subdirectories:
lib
models
observers
workers
In the spec_helper.rb file, how do I tell rspec to exclude all spec files in the lib subdirectory?
Spork.prefork do
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.mock_with :rspec
config.use_transactional_fixtures = false
config.before(:suite) do
DatabaseCleaner.clean_with :truncation
DatabaseCleaner.strategy = :transaction
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
config.treat_symbols_as_metadata_keys_with_true_values = true
config.filter_run :focus => true
end
end
Spork.each_run do
FactoryGirl.reload
end
FYI - I'm using guard to auto-reload tests.
Not sure how to exclude but you can include a list in guard like this:
guard 'rspec', :spec_paths => ['spec/models', 'spec/workers', 'spec/observers'] do
# ...
end
One solution is Exclusion Filters:
RSpec.configure do |c|
# declare an exclusion filter
c.filter_run_excluding :broken => true
end
describe "something" do
it "does one thing" do
end
# tag example for exclusion by adding metadata
it "does another thing", :broken => true do
end
end
exclusion flag can be applied to describe and context too.
Also, this is useful config option:
RSpec.configure do |c|
c.run_all_when_everything_filtered = true
end
So if everything in /lib is excluded, you will still be able
to run specs manually with rspec spec/lib/
Related
I've written a simple plugin that generates a small JSON file
module Jekyll
require 'pathname'
require 'json'
class SearchFileGenerator < Generator
safe true
def generate(site)
output = [{"title" => "Test"}]
path = Pathname.new(site.dest) + "search.json"
FileUtils.mkdir_p(File.dirname(path))
File.open(path, 'w') do |f|
f.write("---\nlayout: null\n---\n")
f.write(output.to_json)
end
# 1/0
end
end
end
But the generated JSON file gets deleted every time Jekyll runs to completion. If I uncomment the division by zero line and cause it to error out, I can see that the search.json file is being generated, but it's getting subsequently deleted. How do I prevent this?
I found the following issue, which suggested adding the file to keep_files: https://github.com/jekyll/jekyll/issues/5162 which worked:
The new code seems to avoid search.json from getting deleted:
module Jekyll
require 'pathname'
require 'json'
class SearchFileGenerator < Generator
safe true
def generate(site)
output = [{"title" => "Test"}]
path = Pathname.new(site.dest) + "search.json"
FileUtils.mkdir_p(File.dirname(path))
File.open(path, 'w') do |f|
f.write("---\nlayout: null\n---\n")
f.write(output.to_json)
end
site.keep_files << "search.json"
end
end
end
Add your new page to site.pages :
module Jekyll
class SearchFileGenerator < Generator
def generate(site)
#site = site
search = PageWithoutAFile.new(#site, site.source, "/", "search.json")
search.data["layout"] = nil
search.content = [{"title" => "Test 32"}].to_json
#site.pages << search
end
end
end
Inspired by jekyll-feed code.
I am very new on Sketchup and ruby , I have worked with java and c# but this is the first time with ruby.
Now I have one problem, I need to serialize all scene in one json (scene hierarchy, object name, object material and position this for single object) how can I do this?
I have already done this for unity3D (c#) without a problem.
I tried this:
def main
avr_entities = Sketchup.active_model.entities # all objects
ambiens_dictionary = {}
ambiens_list = []
avr_entities.each do |root|
if root.is_a?(Sketchup::Group) || root.is_a?(Sketchup::ComponentInstance)
if root.name == ""
UI.messagebox("this is a group #{root.definition.name}")
if root.entities.count > 0
root.entities.each do |leaf|
if leaf.is_a?(Sketchup::Group) || leaf.is_a?(Sketchup::ComponentInstance)
UI.messagebox("this is a leaf #{leaf.definition.name}")
end
end
end
else
# UI.messagebox("this is a leaf #{root.name}")
end
end
end
end
Have you tried the JSON library
require 'json'
source = { a: [ { b: "hello" }, 1, "world" ], c: 'hi' }.to_json
source.to_json # => "{\"a\":[{\"b\":\"hello\"},1,\"world\"],\"c\":\"hi\"}"
Used the code below to answer a question Here, but it might also work here.
The code can run outside of SketchUp for testing in the terminal. Just make sure to follow these steps...
Copy the code below and paste it on a ruby file (example: file.rb)
Run the script in terminal ruby file.rb.
The script will write data to JSON file and also read the content of JSON file.
The path to the JSON file is relative to the ruby file created in step one. If the script can't find the path it will create the JSON file for you.
module DeveloperName
module PluginName
require 'json'
require 'fileutils'
class Main
def initialize
path = File.dirname(__FILE__)
#json = File.join(path, 'file.json')
#content = { 'hello' => 'hello world' }.to_json
json_create(#content)
json_read(#json)
end
def json_create(content)
File.open(#json, 'w') { |f| f.write(content) }
end
def json_read(json)
if File.exist?(json)
file = File.read(json)
data_hash = JSON.parse(file)
puts "Json content: #{data_hash}"
else
msg = 'JSON file not found'
UI.messagebox(msg, MB_OK)
end
end
# # #
end
DeveloperName::PluginName::Main.new
end
end
I have the code that implement csv upload like this:
def Hotel.import(file)
CSV.foreach(file.path, headers: true) do |row|
product = find_by_id(row["id"]) || new
product.attributes = row.to_hash
product.save
end
end
def import
Hotel.import(params[:file])
redirect_to root_url, notice: "Product was successfully Imported."
end
so how do I write rspec test for this?
There are lots of ways to write controller specs. There are many good resources online outlining how to write them in different styles. I suggest starting with the RSpec docs on controller specs:
https://github.com/rspec/rspec-rails#controller-specs
https://www.relishapp.com/rspec/rspec-rails/v/2-14/docs/controller-specs
In general they go something like:
require "spec_helper"
describe ProductsController do
describe "POST #import" do
it "redirects to the home page" do
allow(Hotel).to receive(:import).with("foo.txt")
post :import, file: "foo.txt"
expect(response).to redirect_to root_url
end
it "adds a flash notice" do
allow(Hotel).to receive(:import).with("foo.txt")
post :import, file: "foo.txt"
expect(flash[:notice]).to eq "Product was successfully imported."
end
it "imports the hotel file" do
expect(Hotel).to receive(:import).with("foo.txt")
post :import, file: "foo.txt"
end
end
end
If any one needed model tests for rspec.
require 'rails_helper'
RSpec.describe Product, type: :model do
describe 'import' do
before :each do
#file = fixture_file_upload('data.csv', 'csv')
end
context 'when file is provided' do
it 'imports products' do
Product.import(#file)
expect(Product.find_by(part_number: '0121G00047P').description)
.to eq 'GALV x FAB x .026 x 29.88 x 17.56'
end
end
end
end
I have my Report model:
class Report < ActiveRecord::Base
belongs_to :user
attr_accessible :ready_status, :document
mount_uploader :document, DocumentUploader
def attach( report_file )
self.update_attributes( :document => File.open( report_file ), :ready_status => true )
end
end
This model has attach metod, which i use to save document and other param. Now i want to test that this function works.
/spec/models/report_spec.rb
# encoding: utf-8
require 'spec_helper'
describe Report do
before(:each) do
#user = User.make!
end
...
context "File's saving" do
before(:each) do
#report = #user.reports.create
#csv_report_file = "#{Rails.root}/spec/files/report.csv"
end
it "CSV should be saved" do
csv_report_filename = #csv_report_file.split("/").last
#report.attach #csv_report_file
#report.reload
#report.document.file.filename.should == csv_report_filename
end
end
end
When i try to saving file from /spec/files i get such error:
Report File's saving CSV should be saved
Failure/Error: #report.document.file.filename.should == csv_report_filename
NoMethodError:
undefined method `filename' for nil:NilClass
But when i try another file from another folder (for example "#{Rails.root}/samples/my-report.csv") then my test passes.
How can i fix that?
Oh, i found the answer. Carrierwave doesn't save empty file and i had one. When i added some data in the file (/spec/files/report.csv) my problem has gone.
Is it possible to alias a namespace in Rake?
I like how you can alias tasks:
task :commit => :c
Would love to be able to do something like this:
namespace :git => :g
With
task :commit => :c
you don't define an alias, you set a prerequisite.
When you call :commit the prerequsite :c is called first.
As long as there is only one prerequsite and :commit does not contain own code, it may look like an alias, but it is not.
Knowing that, you may 'alias' your namespace, if you define a default task for your namespace and set a prerequisite for this task (and the prerequisite may be again a default task of another namespace).
But I think, there is no need of aliasing namespaces. It would be enough, if you define a default task for namepsaces and perhaps 'alias' that task.
After reading the question again I have an alternative idea, based on Is there a “method_missing” for rake tasks?:
require 'rake'
namespace :long_namespace do
task :a do |tsk|
puts "inside #{tsk.name}"
end
end
rule "" do |tsk|
aliastask = tsk.name.sub(/short:/, 'long_namespace:')
Rake.application[aliastask].invoke
end
Rake.application['short:a'].invoke
The rule defines a task_missing-rule and tries to replace the namespace (in the example it replaces 'short' with 'long_namespace').
Disadvantage: An undefined task returns no error. So you need an adapted version:
require 'rake'
namespace :long_namespace do
task :a do |tsk|
puts "inside #{tsk.name}"
end
end
rule "" do |tsk|
aliastask = tsk.name.sub(/short:/, 'long_namespace:')
if Rake.application.tasks.map{|tsk| tsk.name }.include?( aliastask )
Rake.application[aliastask].invoke
else
raise RuntimeError, "Don't know how to build task '#{tsk.name}'"
end
end
Rake.application['short:a'].invoke
Rake.application['short:undefined'].invoke
And a more generalized version with a new method aliasnamespace to define the alias-namespaces:
require 'rake'
#Extend rake by aliases for namespaces
module Rake
ALIASNAMESPACES = {}
end
def aliasnamespace(alias_ns, original_ns)
Rake::ALIASNAMESPACES[alias_ns] = original_ns
end
rule "" do |tsk|
undefined = true
Rake::ALIASNAMESPACES.each{|aliasname, origin|
aliastask = tsk.name.sub(/#{aliasname}:/, "#{origin}:")
if Rake.application.tasks.map{|tsk| tsk.name }.include?( aliastask )
Rake.application[aliastask].invoke
undefined = false
end
}
raise RuntimeError, "Don't know how to build task '#{tsk.name}'" if undefined
end
#And now the usage:
namespace :long_namespace do
task :a do |tsk|
puts "inside #{tsk.name}"
end
end
aliasnamespace :short, 'long_namespace'
Rake.application['short:a'].invoke
#~ Rake.application['short:undefined'].invoke