I want to alter I18n.translate method in existing project.
require 'I18n'
module I18n
alias_method :old_translate, :translate
def translate(*args)
old_translate(*args) + 'blabla'
end
alias_method :t, :translate
end
This generates:
Uncaught exception: Missing helper file helpers/I18n.rb
What I do wrong and where I should put this code?
config/locales/en.yml:
en:
wtfblabla: hello
test.rb:
require 'i18n'
module I18n
class<< self
alias_method :old_translate, :translate
def translate(*args)
old_translate(*args) + 'blabla'
end
alias_method :t, :translate
end
end
I18n.load_path += p(Dir[File.join(File.dirname(__FILE__), 'config', 'locales', '*.yml').to_s])
p I18n.t "wtfblabla"
output:
["./config/locales/en.yml"]
"helloblabla"
Related
I installed 'rails_admin' gem for an admin panel. I already have 'will_paginate-bootstrap' gem installed.
When i click on a model name, I get this error
Create a kaminari.rb in app/config/initializers and,
Kaminari.configure do |config|
config.page_method_name = :per_page_kaminari
end
as you have will_paginate enabled, create will_paginate.rb in initializers and,
if defined?(WillPaginate)
module WillPaginate
module ActiveRecord
module RelationMethods
def per(value = nil) per_page(value) end
def total_count() count end
def first_page?() self == first end
def last_page?() self == last end
end
end
module CollectionMethods
alias_method :num_pages, :total_pages
end
end
end
This should work for rails_admin with will_paginate
I have a rails 3.2.16 app that has a model and controller to upload a csv file that contains a list of customer details. In the app itself this works fine, however I can't get the test to work.
I basically get an error that says
undefined method 'first_name,last_name,address_1,address_2,city .... etc.'
So it is trying to use the first line of the csv file as a method ... ?
The files I am using are shown below
spec (the commented out lines show things that I have tried along the way having seen other issues in SO)
it "upload a file with correct properties" do
#include Rack::Test::Methods
# #file = fixture_file_upload(Rails.root.join('spec/fixtures/files/cust-imp-good.csv'), 'text/csv')
#file = Rack::Test::UploadedFile.new(Rails.root.join('spec/fixtures/files/cust-imp-good.csv'), 'text/csv')
post :create, :customer_import => #file
response.should be_success
end
uploader model
class CustomerImport #< ActiveRecord::Base
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
attr_accessor :file
def initialize(attributes = {})
debugger
attributes.each { |name, value| send("#{name}=", value) }
end
def persisted?
false
end
def save
if imported_customers.map(&:valid?).all?
valid_ids = true
dive_shop_ids = DiveShop.ids_array
discount_level_ids = DiscountLevel.ids_array
imported_customers.each_with_index do |customer, index|
if !dive_shop_ids.include?(customer.dive_shop_id)
errors.add :base, "Row #{index+2}: dive_shop_id #{customer.dive_shop_id} is not valid"
valid_ids = false
end
if !discount_level_ids.include?(customer.discount_level_id)
errors.add :base, "Row #{index+2}: discount_level_id #{customer.discount_level_id} is not valid"
valid_ids = false
end
end
if valid_ids
imported_customers.each(&:save!)
return_val = imported_customers.count
else
false
end
else
imported_customers.each_with_index do |customer, index|
customer.errors.each do |message|
errors.add :base, "Row #{index+2}: #{message}"
end
end
false
end
end
def imported_customers
#imported_customers ||= ImportRecord.load_imported_records("Customer", file)
end
end
From the error shown below I can see that it is failing in the initializer. Although if I put a debugger in there the initializer looks to be OK.
Output from debugger inside initializer
rdb:1 attributes
Rack::Test::UploadedFile:0x0000000b089a98 #content_type="text/csv", #original_filename="cust-imp-good.csv", #tempfile=#<File:/tmp/cust-imp-good.csv20131212-26548-ynutnh>>
rdb:1
Output from rspec failure message
Failures:
1) CustomerImportsController POST 'create' upload a file with correct properties
Failure/Error: post :create, :customer_import => #file
NoMethodError:
undefined method `first_name,last_name,address1,address2,address3,city,state,country,postcode,telephone,email,dob,local_contact,emergency_name,emergency_number,dive_shop_id,discount_level_id
=' for #<CustomerImport:0x0000000a5f7580>
# ./app/models/customer_import.rb:10:in `block in initialize'
# ./app/models/customer_import.rb:10:in `initialize'
# ./app/controllers/customer_imports_controller.rb:14:in `new'
# ./app/controllers/customer_imports_controller.rb:14:in `create'
# ./spec/controllers/customer_imports_controller_spec.rb:20:in `block (3 levels) in <top (required)>'
any help would be much appreciated I tried the solution shown in Undefined Method 'NameOfField' for #<Model:0x000...> i.e rake: db:test:prepare and bundle exec rspec . but this didn't work either
EDIT to include controller code
class CustomerImportsController < ApplicationController
before_filter do
#menu_group = "diveshop"
end
def new
#customer_import = CustomerImport.new
end
def create
if params[:customer_import] != nil
#customer_import = CustomerImport.new(params[:customer_import])
return_value = #customer_import.save # need to add #customer_import.file here
if return_value != false
addauditlog("A bulk import of customers was carried out")
redirect_to customers_url, notice: "Imported #{return_value} customers successfully."
else
render :new
end
else
flash[:error] = "You have not selected a file"
redirect_to new_customer_import_url
end
end
end
In creating the new model instance, your controller seems to have passed a hash as a parameter with a key whose value is the first line of the csv file. You'll need to share the controller code and the first line of the file you've updated in order to be able to confirm that and provide more information.
I'm trying to set up Rspec and FactoryGirl on an existing Rails 3 project which previously has had no automated testing.
The error I'm getting when running the test as below is Factory not registered: admin
I can't see why this would be failing, it happens for every test through my specs that use a factory.
/Gemfile.rb (concatenated for brevity)
group :development, :test do
gem 'rspec-rails'
gem 'factory_girl_rails
end
/config/application.rb (concatenated for brevity)
config.generators do |g|
g.test_framework :rspec, fixture: true
g.fixture_replacement :factory_girl, dir: "spec/factories"
end
/spec/spec_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'capybara/mechanize'
require 'factory_girl_rails'
HTTPI.log = false
FactoryGirl.factories.clear
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.mock_with :rspec
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_base_class_for_anonymous_controllers = false
config.expect_with :rspec do |c|
c.syntax = :expect
end
config.include Devise::TestHelpers, type: :controller
config.extend ControllerMacros, type: :controller
end
/spec/support/controller_macros.rb
module ControllerMacros
def login_admin
before(:each) do
#request.env["devise.mapping"] = Devise.mappings[:admin]
sign_in FactoryGirl.create(:admin)
end
end
end
/spec/factories/users.rb
FactoryGirl.define do
factory :admin do
sequence(:email) {|n| "user#{n}#local.test"}
password "password"
password_confirmation "password"
association :user_role, factory: :admin_role
trait :as_reseller do
association :user_role, factory: :reseller_role
end
trait :as_customer do
association :user_role, factory: :customer_role
end
end
factory :reseller, parent: :admin do
as_reseller
end
factory :customer, parent: :admin do
as_customer
end
end
/spec/controllers/accounts_controller_spec.rb
describe AccountCodesController do
describe "as administrator" do
login_admin
describe "GET 'index'" do
it "returns http success" do
get 'index'
response.should be_success
end
end
end
end
This line FactoryGirl.factories.clear confuse me a lot.
According to doc you needn't do any spec_helper modification (if you use it in Rails app and through Bundle).
This is my spec_helper in one of my APP and I use factories in it successfully.
It's explain on the link
The stable documentation is here :
http://github.com/thoughtbot/factory_girl/tree/1.3.x
I've got the following initializer:
app/config/initializers/store_location.rb
module StoreLocation
def self.skip_store_location
[
Devise::SessionsController,
Devise::RegistrationsController,
Devise::PasswordsController
].each do |controller|
controller.skip_before_filter :store_location
end
end
self.skip_store_location
end
Relevant parts of my ApplicationController:
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :convert_legacy_cookies
before_filter :store_location
alias_method :devise_current_user, :current_user
def current_user
# do something
end
private
def store_location
# store location
end
Plus this in
config/environments/development.rb
Foo::Application.configure do
# normal rails stuff
config.to_prepare do
StoreLocation.skip_store_location
end
end
If I let RSpec/Rails run the self.skip_store_location I'm getting the following error:
/foo/app/controllers/application_controller.rb:7:in `alias_method': undefined method `current_user' for class `ApplicationController' (NameError)
If I remove the call, everything is back to normal (except the filter is run, as expected). I'm guessing that I mess up dependency loading somehow?
The problem is that you use alias_method before the method is defined in ApplicationController. To fix the problem, move the line
alias_method :devise_current_user, :current_user
below
def current_user
# do something
end
It's a bit misleading that the error appears when running skip_store_location. I assume that happens because skip_store_location loads several controllers, and one of them is a subclass of ApplicationController.
I saw various versions of how to setup a global HTTP_REFERER in RSpec, but none of them worked with RSpec 2.6.4:
RSpec.configure do |config|
config.before(:each, :type => :controller) do
request.env["HTTP_REFERER"] = root_url
end
end
The request is always nil:
undefined method `env' for nil:NilClass
RSpec is calling this:
def self.eval_before_eachs(example)
world.run_hook_filtered(:before, :each, self, example.example_group_instance, example)
ancestors.reverse.each { |ancestor| ancestor.run_hook(:before, :each, example.example_group_instance) }
end
# spec/support/http_referer.rb
module HttpReferer
def self.included(base)
base.class_eval do
setup :setup_http_referer if respond_to?(:setup)
end
end
def setup_http_referer
#request.env["HTTP_REFERER"] = "/back"
end
end
# spec/spec_helper.rb
RSpec.configure do |config|
config.include HttpReferer, :type => :controller
end
This link may help get you pointed in the right direction...
https://github.com/plataformatec/devise/wiki/How-To:-Controllers-and-Views-tests-with-Rails-3-%28and-rspec%29
You'll need to make a module like...
module Foo
def set_referer
#request.env["HTTP_REFERER"] = root_url
end
end
Then configure RSpec...
RSpec.configure do |config|
config.extend Foo, :type => :controller
end
Then call it in each of your controller specs...
describe MyController do
set_referer
end
We're using a similar approach to set our session cookie, but YMMV.