TDD: Rspec Ruby MongoDB/Ruby Mongo Driver - ruby-on-rails-3

how can I use TDD with MongoDB as my second database?
Thanks
Edit:
Using Rspec or anything else that allows me to test it.

[Update]
With MongoMapper set up you can easily use the mongodb connection directly
mongodb = MongoMapper.database
collection = mongodb.collection("my_collection")
collection.find.first
=> {"_id"=>BSON::ObjectId('4e43dfc75d1e1e0001000001'), "key1"=>"val1" }
this other SO Q/A is even more direct, using javascript functions like MongoMapper.database.eval(Mongo::Code.new('function(){ return 11 + 6; })
[/update]
I have such a polyglot architecture, some models with postgresql, others as mongo documents. I'm not really sure what you're asking, so I'll jump straight in and post most my configuration here. It includes my hacks, you probably find more beautiful config elsewhere.
I put the setup in a gist
https://gist.github.com/957341
OK, so here's a document with embedded document, then the spec. I wrote the specs one by one, so they're kinda test driven.
class MyDocument
include MongoMapper::Document
key :title, String
key :published_at, Time, :index => true
key :collaborators, Array
many :my_embedded_documents
end
class MyEmbeddedDocument
include MongoMapper::EmbeddedDocument
key :title, String
key :author, String
embedded_in :my_document
end
the spec
require "spec_helper"
describe MyDocument do
before do
#md = MyDocument.create(:title => "Example", :collaborators => ["mongomapper", "rspec", "oma"] )
end
it "should have title" do
found = MyDocument.find(#md.id)
found.title.should == "Example"
end
it "should have two my_documents" do
MyDocument.create
MyDocument.count.should == 2
end
it "should be able to fetch embedded documents" do
#md.my_embedded_documents << MyEmbeddedDocument.new(:title => "The King", :name => "Elvis Presley")
#md.my_embedded_documents.build(:title => "Embedded example", :name => "Embeddo")
#md.save!
MyDocument.where(:title => "Example").first.should == #md #findMyEmbeddedDocument.count.should == 2
end
end
spec_helper.rb
RSpec.configure do |config|
#...
config.after(:each) do
MongoMapper.database.collections.each(&:remove)
end
end
I don't know what you wanted for answers, but I hope this will be of help to somebody.

From what I can gather, it doesn't appear that your app is sticking to the rails MVC paradigm with its use of this secondary database that apparently doesn't store model data.
I would recommend taking the auxiliary parts of the app that depend on mongo and sticking them into a library. You can make this a gem if it makes sense to use it elsewhere. Then, create a testsuite for the logic of the library using standard testing tools, and integrate into your app either with a simple require, or some directives (depending on what it dies and how you intend to use it).

Related

New to Rails 4 Testing - Need help getting started (rSpec and Devise)

I'm relatively new to testing and very new to Rails 4 and rSpec. I am trying to test a controller that uses Devise for authentication and I am stuck. All of the examples I can find are for Rails 3.
I'm using Rails 4.0.3, Devise 3.2.3, rSpec 2.14.1 and FactoryGirl 4.4.0.
class LessonPlansController < ApplicationController
before_action :authenticate_user!
# GET /lesson_plans
def index
#lesson_plans = current_user.lesson_plans.to_a
end
.
.
.
private
# Use callbacks to share common setup or constraints between actions.
def set_lesson_plan
#lesson_plan = LessonPlan.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def lesson_plan_params
params[:lesson_plan]
end
def lesson_plan_params
params.require(:lesson_plan).permit(:title, :synopsis)
end
end
Here are my factory definitions: (Maybe I don't need to define user_id in the lesson_plan factory?)
FactoryGirl.define do
factory :user do
sequence( :username ) { |n| "user#{n}" }
sequence( :email ) { |n| "foo#{n}#example.com" }
password 'foobarbaz'
password_confirmation 'foobarbaz'
created_at Time.now
updated_at Time.now
end
end
FactoryGirl.define do
factory :lesson_plan do
user_id 1
title "The French Revolution"
synopsis "Background and events leading up to the French Revolution"
end
end
And the test part is where I get stuck.
describe LessonPlansController do
let(:valid_attributes) { { } }
let(:valid_session) { {} }
# describe "GET index" do
it "assigns all lesson_plans as #lesson_plans" do
user=FactoryGirl.create(:user)
sign_in user
lesson_plan = LessonPlan.create! valid_attributes
get :index, {}, valid_session
assigns(:lesson_plans).should eq([lesson_plan])
end
end
I'm not sure what to put in valid_attributes and valid_session (or if I even need them). The test will get as far as signing in the user, but will fail on creation of the lesson_plan. Admittedly this is the default/generated test for rSpec, but I am not sure how to proceed.
Examples I have seen use a before block to set up the user. I haven't been able to find anything on the Devise wiki page covering how to write basic rSpec tests for a controller that requires the user to be logged in. Any pointers would be greatly appreciated!
"I'm not sure what to put in valid_attributes and valid_session (or if I even need them)."
Well that depends what you're testing for.. Say you're testing validations & want to ensure that a record not be created if x column is set to null... then you could try to specifically create a record with invalid attributes (e.g. column: nil) and expect the result to not return true; maybe you want to ensure that it IS created with valid attributes.
You can btw, use `attributes_for(:factory_name)`` since you're using FactoryGirl. And no you don't necessarily need to specify the user's id in your lesson plan factory; unless you always want it to reference user 1. You can simply reference user with no value. Check out http://everydayrails.com/2012/03/12/testing-series-intro.html and especially parts 3-5 for an introduction to testing with RSPec.. I found this a pretty easy to follow guide when I was getting started.

Rails 3 inherited_resources ignores 'defaults' setting

I'm using Inherited resources for my controllers. And now i have model:
class Sms < ActiveRecord::Base
end
And i want controller for it, where i make defaults:
class Admin::SmsesController < Admin::InheritedResources
defaults :resource_class => Sms,
:collection_name => 'smses',
:instance_name => 'sms'
end
but i can not understand, why it still trying to get "Smse" model:
NameError in Admin::SmsesController#index
uninitialized constant Smse
Pls help.
The problem is that Rails doesn't know that the plural of Sms is Smses. If you go to the Rails console you should see that:
> "Sms".pluralize
=> "Sms"
> "Smses".singularize
=> "Smse"
When faced with a plural it doesn't recognise, singularize just truncates the final "s", which is why your app is looking for a nonexistent Smse model.
You will save yourself a lot of headaches by configuring Rails to pluralize/singularize your models correctly. In the file config\initializers\inflections.rb you should find some examples of how to do this. What you want is:
ActiveSupport::Inflector.inflections do |inflect|
inflect.irregular 'sms', 'smses'
end
Then I don't think you should need to put the defaults option in there at all - it should all work out of the box.

Mongomapper: Embedded document does not work properly

I don't know what's going on but I can't seem to find working a very small piece of code. I used mongomappper without embedded documents and everything went fine. Using an embedded document I hit the brick wall. I'm following the instructions on the mongomapper homepage using the Rails console:
Here are my models:
class Assessment
include Mongomapper::Document
many :sections
end
class Section
include MongoMapper::EmbeddedDocument
key :title, String
validates_presence_of :title
end
When I run:
a = Assessment.create(:sections => [ Section.new(:title => 'test') ] )
I will get the following output:
=> #<Assessment _id: BSON::ObjectId('4e71efce69a74c0fb6000002'), sections: nil>
I also tried with a = Assessment.new(), a.sections << Section.new(:title => "test")
but the same result.
Why is there nothing inside sections?
Including:
attr_accessible :sections
should make the create work (at it does for me). And you'll probably want to add:
validates_associated :sections
to make your Assessment validate the embedded Sections the way you'd probably expect.
Yeah, a couple years late but I just had to sort this problem out and Google brought me here.

Rails ActiveRecord query

My question is twofold... Primarily, I am trying to figure out how to ask > or < when filtering this query. You can see at the end I have .where(:created_at > 2.months.ago) and that is improper syntax, but I'm not sure the correct way to call something similar.
Secondly, this is a bit of a long string and is going to get longer as the are more conditions I have to factor in. Is there a cleaner way of building this, or is a long string of conditions like this pretty standard?
class PhotosController < ApplicationController
def showcase
#photos = Photo.order(params[:sort] || 'random()').search(params[:search]).paginate(:per_page => 12, :page => params[:page]).where(:created_at > 2.months.ago)
end
Thanks.
Unfortunately you've hit a sore point in the ActiveRecord querying api. There is no standard, out of the box way to do this. You can do date ranges very easily, but < and > have no easy path. However Arel, the underlying SQL engine, can do this very easily. You could write a simple scope to handle it thusly:
scope :created_after, lambda {|date| where arel_table[:created_at].gt(date) }
And you could refactor this easily to take a column, or gt versus lt, etc.
Other people have solved this problem already, however, and you could take advantage of their work. One example is MetaWhere, which adds a bunch of syntactic sugar to your queries. For example, using it you might write:
Article.where(:title.matches => 'Hello%', :created_at.gt => 3.days.ago)
On #2, scopes do tend to get long. You might look into the gem has_scope, which helps to alleviate this by defining scopes on the controller in an analogous way to how they are defined on the model. An example from the site:
# The model
# Note it's using old Rails 2 named_scope, but Rails 3 scope works just as well.
class Graduation < ActiveRecord::Base
named_scope :featured, :conditions => { :featured => true }
named_scope :by_degree, proc {|degree| { :conditions => { :degree => degree } } }
end
# The controller
class GraduationsController < ApplicationController
has_scope :featured, :type => :boolean
has_scope :by_degree
def index
#graduations = apply_scopes(Graduation).all
end
end
You can do where(["created_at > ?", 2.months.ago]) for your first question.
For your second question there are several solutions :
You can use scopes to embed the conditions in them and then combine them.
You can break the line in multiple lines.
You can keep it like this if you have a large screen and you don't work with any other people.

Rspec 2 and Rails 3 stubbing / mocking

I am currently in the process of migration to rails 3 from rails 2 in a large application. In our functional specs, we have alot of stuff like this:
#model = Factory :model
#child = Factory :child
Model.stub!(:find).and_return(#model)
Child.stub!(:find).and_return(#child)
...
#child.should_receive(:method).twice
The main issue is that if I let it hit DB and get actual instance of child, real :method makes tests too complex (need two big factories) and slow.
In code we use various ways to get items: find, dynamic finders, etc
#model = Model.find(1)
#child = #model.children.find_by_name(name)
How would you advice to move this logic to rails 3? Any advice on another stubbing/mocking library maybe?
Normally you would mock the model inside controller specs:
Model.stub!(:find).and_return(mock_model('Model'))
Child.stub!(:find).and_return(mock_model('Child'))
However, when you've got gem "rspec-rails", "~> 2.0" in your rails 3 app's Gemfile, then the standard rails scaffold generator will use rspec to generate specs for you, so running rails generate scaffold MyResource will generate some example specs for you.
The following is a lightly annotated version of what rails/rspec will generate for controller specs, so I suppose this should be considered "The RSpec Way".
describe AccountsController do
# Helper method that returns a mocked version of the account model.
def mock_account(stubs={})
(#mock_account ||= mock_model(Account).as_null_object).tap do |account|
account.stub(stubs) unless stubs.empty?
end
end
describe "GET index" do
it "assigns all accounts as #accounts" do
# Pass a block to stub to specify the return value
Account.stub(:all) { [mock_account] }
get :index
# Assertions are also made against the mock
assigns(:accounts).should eq([mock_account])
end
end
describe "GET show" do
it "assigns the requested account as #account" do
Account.stub(:find).with("37") { mock_account }
get :show, :id => "37"
assigns(:account).should be(mock_account)
end
end
describe "GET new" do
it "assigns a new account as #account" do
Account.stub(:new) { mock_account }
get :new
assigns(:account).should be(mock_account)
end
end
end