I'm using Devise to manage users and my goal get the current user to be saved with the created record.
The current user is saved in the controller but my Rspec is wrong!
Thank you all for your help.
My record Model
class Record < ActiveRecord::Base
#Associations
belongs_to :user
# Validations
validates :title, :user, presence: true
end
My record Controller
class RecordsController < ApplicationController
before_action :find_record, only: [:show, :edit, :update, :destroy]
def create
#record = Record.new(record_params)
if #record.save
redirect_to #record
else
#records = Record.all
render 'index'
end
end
def update
if #record.update(record_params)
flash[:notice] = "The record was updated successfully"
redirect_to #record
else
render 'edit'
end
end
private
def find_record
#record = Record.find(params[:id])
end
def record_params
params.require(:record).permit(:title, :description, :user_id).merge(user: current_user) # as suggested
end
end
My Rspec
require 'rails_helper'
describe RecordsController do
let(:record) { create(:record) }
let(:user) { create(:user) }
let(:title) { "Some title I would like to put in my record" }
let(:description) { "description I would like to put in my record" }
describe "#create" do
it "creates a new record with the given title and description" do
expect do
post :create, record: { title: title, description: description, user_id: user }
end.to change { Record.count }.by(1)
expect(response).to redirect_to(assigns[:record])
expect(assigns[:record].title).to eq(title)
expect(assigns[:record].description).to eq(description)
end
it "fails to create a record and returns to the index page" do
expect(post :create, record: { description: description }).to render_template(:index)
expect(assigns[:records]).to eq(Record.all)
end
end
describe "#update" do
it "find the records and sets the new given values" do
put :update, { id: record.id, record: { title: title, description: description } }
record.reload
expect(record.title).to eq(title)
expect(record.description).to eq(description)
expect(flash[:notice]).to eq("The record was updated successfully")
end
it "fails to create a record and returns to the edit page" do
expect(put :update, { id: record.id, record: { title: "" } }).to render_template(:edit)
end
end
end
Now with the current user being saved Rspec throws me errors in create and update:
1) RecordsController#create creates a new record with the given title and description
Failure/Error: post :create, record: { title: title, description: description, user_id: user }
NoMethodError:
undefined method `authenticate' for nil:NilClass
# ./app/controllers/records_controller.rb:42:in `record_params'
# ./app/controllers/records_controller.rb:9:in `create'
# ./spec/controllers/records_controller_spec.rb:36:in `block (4 levels) in <top (required)>'
# ./spec/controllers/records_controller_spec.rb:35:in `block (3 levels) in <top (required)>'
# -e:1:in `<main>'
2) RecordsController#create fails to create a record and returns to the index page
Failure/Error: expect(post :create, record: { description: description }).to render_template(:index)
NoMethodError:
undefined method `authenticate' for nil:NilClass
# ./app/controllers/records_controller.rb:42:in `record_params'
# ./app/controllers/records_controller.rb:9:in `create'
# ./spec/controllers/records_controller_spec.rb:46:in `block (3 levels) in <top (required)>'
# -e:1:in `<main>'
3) RecordsController#update find the records and sets the new given values
Failure/Error: put :update, { id: record.id, record: { title: title, description: description } }
NoMethodError:
undefined method `authenticate' for nil:NilClass
# ./app/controllers/records_controller.rb:42:in `record_params'
# ./app/controllers/records_controller.rb:20:in `update'
# ./spec/controllers/records_controller_spec.rb:62:in `block (3 levels) in <top (required)>'
# -e:1:in `<main>'
4) RecordsController#update fails to create a record and returns to the edit page
Failure/Error: expect(put :update, { id: record.id, record: { title: "" } }).to render_template(:edit)
NoMethodError:
undefined method `authenticate' for nil:NilClass
# ./app/controllers/records_controller.rb:42:in `record_params'
# ./app/controllers/records_controller.rb:20:in `update'
# ./spec/controllers/records_controller_spec.rb:72:in `block (3 levels) in <top (required)>'
You need to login the user first before you can use the current_user.
Something like:
before do
sign_in :user, create(:user)
end
Also checkout How To: Test controllers with Rails 3 and 4 (and RSpec)
Related
I'm using latest version of Solidus e-commerce (fork of Spree) and I'm having this issue. To describe it quickly:
In Admin I create Spree::Membership record
after_save callback in Spree::Membership creates Product and 2 variants
This code works when I run the server, but when I'm trying to use Rspec it gives me this error:
Failure/Error: reload.product.setup_membership_variants
NoMethodError:
undefined method `setup_membership_variants' for nil:NilClass
# ./app/models/spree/membership.rb:26:in `block in setup_product'
# ./app/models/spree/membership.rb:18:in `setup_product'
# /box/gems/factory_girl-4.8.0/lib/factory_girl/configuration.rb:18:in `block in initialize'
# /box/gems/factory_girl-4.8.0/lib/factory_girl/evaluation.rb:15:in `create'
# /box/gems/factory_girl-4.8.0/lib/factory_girl/strategy/create.rb:12:in `block in result'
# /box/gems/factory_girl-4.8.0/lib/factory_girl/strategy/create.rb:9:in `tap'
# /box/gems/factory_girl-4.8.0/lib/factory_girl/strategy/create.rb:9:in `result'
# /box/gems/factory_girl-4.8.0/lib/factory_girl/factory.rb:42:in `run'
# /box/gems/factory_girl-4.8.0/lib/factory_girl/factory_runner.rb:29:in `block in run'
# /box/gems/factory_girl-4.8.0/lib/factory_girl/factory_runner.rb:28:in `run'
# /box/gems/factory_girl-4.8.0/lib/factory_girl/strategy_syntax_method_registrar.rb:20:in `block in define_singular_strategy_method'
# ./spec/controllers/spree/premium_controller_spec.rb:4:in `block (2 levels) in <top (required)>'
# ./spec/controllers/spree/premium_controller_spec.rb:33:in `block (6 levels) in <top (required)>'
# ./spec/controllers/spree/premium_controller_spec.rb:53:in `block (8 levels) in <top (required)>'
# ./spec/controllers/spree/premium_controller_spec.rb:53:in `block (7 levels) in <top (required)>'
Here is code I'm using:
membership.rb
class Spree::Membership < Spree::Base
has_many :active_memberships, class_name: 'Spree::ActiveMembership', dependent: :destroy
has_one :membership_product, class_name: "Spree::MembershipProduct", dependent: :destroy
has_one :product, through: :membership_product, source: :product
validates :name, presence: true
validates :monthly_quota, presence: true
validates :price, presence: true
after_save :setup_product
private
def setup_product
if product.nil?
ActiveRecord::Base.transaction do
create_membership_product(
product: Spree::Product.create(
name: name,
price: price,
shipping_category: Spree::ShippingCategory.find_by(name: "Default")
)
)
reload.product.setup_membership_variants
end
else
product.update(name: name, price: price)
end
end
end
product_decorator.rb
Spree::Product.class_eval do
def setup_membership_variants
ot = Spree::OptionType.find_or_create_by(name: "Membership")
option_types << ot
if ot.option_values.empty?
["Monthly", "Yearly"].each do |freq|
ot.option_values.create(name: freq, presentation: freq)
end
end
month = variants.create(is_master: false, price: price, track_inventory: false)
month.option_values << Spree::OptionValue.find_by(name: "Monthly")
year = variants.create(is_master: false, price: price * 12, track_inventory: false)
year.option_values << Spree::OptionValue.find_by(name: "Yearly")
end
end
membership.rb factory
FactoryGirl.define do
factory :membership, class: Spree::Membership do
name {FFaker::Lorem.word}
monthly_quota { rand(10..200) }
price { rand(10..200) }
trait :unnamed do
name nil
end
trait :without_quota do
monthly_quota nil
end
trait :priceless do
price nil
end
end
end
example of controller test
require 'rails_helper'
RSpec.describe Spree::PremiumController, type: :controller do
let(:valid_membership) { create(:membership) }
let(:variant) { create(:master_variant) }
context "#show" do
it "returns http success" do
get :show
expect(response).to have_http_status(:success)
end
it "returns all memberships" do
get :show
expect(assigns[:memberships]).to include(valid_membership)
end
end
context "#create" do
let!(:store) { create(:store) }
context "user not logged" do
context "valid attributes" do
context "user doesn't exist in database" do
subject do
post(:create, params: {
premium: {
first_name: "Ondrej",
last_name: "Kubala",
email: "ondrej#bala.com",
password: "test123",
password_confirmation: "test123",
membership_id: valid_membership.id,
payment_frequency: "1", #monthly yearly is 2
cc_number: "4111111111111111",
cc_exp_date: "10/22",
cvv: "123"
}
})
end
it "creates user with valid attributes" do
expect { subject }.to change { Spree::User.count }.from(0).to(1)
end
it "logs in user" do
expect(controller.warden).to receive(:set_user)
subject
end
context "create order with variant" do
it "should handle population" do
expect { subject }.to change { Spree::Order.count }.by(1)
user = Spree::User.find_by email: "ondrej#bala.com"
order = user.orders.last
expect(response).to redirect_to go_premium_path
expect(order.line_items.size).to eq(1)
# line_item = order.line_items.first
# expect(line_item.variant_id).to eq(valid_membership.reload.product.variants.)
end
it "charges credit card"
it "should redirect to account page"
end
end
context "user already exists"
end
context "wrong user attributes" do
end
context "wrong payment attributes" do
end
end
context "user is logged in" do
let(:user) { create(:user) }
before do
allow(controller).to receive_messages try_spree_current_user: user
allow(controller).to receive_messages spree_current_user: user
end
it "doesn't create user"
end
end
end
I don't have too much experience in Rspec, but it's weird that it works when server is running in development but in test it gives me that error.
Any idea what is wrong?
My guess would be that product creation call fails for some reason.
Try bang version(product: Spree::Product.create!) to have the error thrown when it occurs.
If product indeed gets created, use pry or byebug to figure out why after reload membership, product is not associated with membership.
I'm using Devise to manage users and my goal get the current user to be saved with the created record.
I have tried to save the current user in the controller or in the _form, but either ways it has failed!
Thank you all for your help.
My record Model
class Record < ActiveRecord::Base
#Associations
belongs_to :user
# Validations
validates :title, :user, presence: true
end
My record Controller
class RecordsController < ApplicationController
before_action :find_record, only: [:show, :edit, :update, :destroy]
def create
#record = Record.new(record_params)
if #record.save
redirect_to #record
else
#records = Record.all
render 'index'
end
end
def update
if #record.update(record_params)
flash[:notice] = "The record was updated successfully"
redirect_to #record
else
render 'edit'
end
end
private
def find_record
#record = Record.find(params[:id])
end
def record_params
params.require(:record).permit(:title, :description, :user_id).merge(user: current_user) # as suggested
end
end
My Rspec
require 'rails_helper'
describe RecordsController do
let(:record) { create(:record) }
let(:user) { create(:user) }
let(:title) { "Some title I would like to put in my record" }
let(:description) { "description I would like to put in my record" }
describe "#create" do
it "creates a new record with the given title and description" do
expect do
post :create, record: { title: title, description: description, user_id: user }
end.to change { Record.count }.by(1)
expect(response).to redirect_to(assigns[:record])
expect(assigns[:record].title).to eq(title)
expect(assigns[:record].description).to eq(description)
end
it "fails to create a record and returns to the index page" do
expect(post :create, record: { description: description }).to render_template(:index)
expect(assigns[:records]).to eq(Record.all)
end
end
describe "#update" do
it "find the records and sets the new given values" do
put :update, { id: record.id, record: { title: title, description: description } }
record.reload
expect(record.title).to eq(title)
expect(record.description).to eq(description)
expect(flash[:notice]).to eq("The record was updated successfully")
end
it "fails to create a record and returns to the edit page" do
expect(put :update, { id: record.id, record: { title: "" } }).to render_template(:edit)
end
end
end
Now with the current user being saved Rspec throws me errors in create and update:
1) RecordsController#create creates a new record with the given title and description
Failure/Error: post :create, record: { title: title, description: description, user_id: user }
NoMethodError:
undefined method `authenticate' for nil:NilClass
# ./app/controllers/records_controller.rb:42:in `record_params'
# ./app/controllers/records_controller.rb:9:in `create'
# ./spec/controllers/records_controller_spec.rb:36:in `block (4 levels) in <top (required)>'
# ./spec/controllers/records_controller_spec.rb:35:in `block (3 levels) in <top (required)>'
# -e:1:in `<main>'
2) RecordsController#create fails to create a record and returns to the index page
Failure/Error: expect(post :create, record: { description: description }).to render_template(:index)
NoMethodError:
undefined method `authenticate' for nil:NilClass
# ./app/controllers/records_controller.rb:42:in `record_params'
# ./app/controllers/records_controller.rb:9:in `create'
# ./spec/controllers/records_controller_spec.rb:46:in `block (3 levels) in <top (required)>'
# -e:1:in `<main>'
3) RecordsController#update find the records and sets the new given values
Failure/Error: put :update, { id: record.id, record: { title: title, description: description } }
NoMethodError:
undefined method `authenticate' for nil:NilClass
# ./app/controllers/records_controller.rb:42:in `record_params'
# ./app/controllers/records_controller.rb:20:in `update'
# ./spec/controllers/records_controller_spec.rb:62:in `block (3 levels) in <top (required)>'
# -e:1:in `<main>'
4) RecordsController#update fails to create a record and returns to the edit page
Failure/Error: expect(put :update, { id: record.id, record: { title: "" } }).to render_template(:edit)
NoMethodError:
undefined method `authenticate' for nil:NilClass
# ./app/controllers/records_controller.rb:42:in `record_params'
# ./app/controllers/records_controller.rb:20:in `update'
# ./spec/controllers/records_controller_spec.rb:72:in `block (3 levels) in <top (required)>'
To add to bo-oz's answer (which should work), you also need to look into foreign keys. Trying to set record_id in your record form simply won't work, and I think demonstrates a misunderstanding in your interpretation of how the system works with this important piece of technology.
Specifically, you need to make sure your user_id attribute is populated before you save the new record. This is a relational database specification, not Rails:
Each time you create an association in Rails, it has to have foreign keys set in the database to enable ActiveRecord (the object association builder inside Rails) to combine the appropriate data together:
#app/models/user.rb
class User < ActiveRecord::Base
has_many :records
end
#app/models/record.rb
class Record < ActiveRecord:Base
#see diagram above -- this has to have user_id in the schema :)
belongs_to :user
end
--
The problem you're having is that you're not setting your user foreign key when you create a record.
Your records table should have a user_id foreign key, so that when Rails pulls out a Record object, it will be able to find the User who's associated to it.
As bo-oz explained, you can achieve this by setting #record.user, you can also set it in the params:
#app/controllers/records_controller.rb
class RecordsController < ApplicationController
def create
#record = Record.new record_params
#record.save ..........
end
private
def record_params
params.require(:record).permit(......).merge(user: current_user)
end
end
Both these answers would set the appropriate foreign key inside your new Record object.
You forgot to assign the user to the new record:
def create
#record = Record.new(record_params)
#record.user = current_user
if #record.save
redirect_to #record
else
#records = Record.all
render 'index'
end
end
I'm currently doing rspec testing on two files and I got these failures regarding undefined methods. I need more calcification on how to exactly fixes these errors,Thanks!
Failures:
1) FavoritesController#create creates a favorite for the current user and specified post
Failure/Error: #post = create(:post)
NoMethodError:
undefined method `create' for #<RSpec::ExampleGroups::FavoritesController::Create:0x007fdabc84f7f8>
# /Users/bryanporras/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.1/lib/action_dispatch/testing/assertions/routing.rb:171:in `method_missing'
# ./spec/controllers/favorites_controller_spec.rb:8:in `block (2 levels) in <top (required)>'
2) FavoritesController#destroy destroys the favorite for the current user and post
Failure/Error: #post = create(:post)
NoMethodError:
undefined method `create' for #<RSpec::ExampleGroups::FavoritesController::Destroy:0x007fdabfe0f3e8>
# /Users/bryanporras/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.1/lib/action_dispatch/testing/assertions/routing.rb:171:in `method_missing'
# ./spec/controllers/favorites_controller_spec.rb:8:in `block (2 levels) in <top (required)>'
3) VotesController#up_vote adds an up-vote to the post
Failure/Error: sign_in #user
NoMethodError:
undefined method `sign_in' for #<RSpec::ExampleGroups::VotesController::UpVote:0x007fdabfe26fe8>
# /Users/bryanporras/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.1/lib/action_dispatch/testing/assertions/routing.rb:171:in `method_missing'
# ./spec/controllers/votes_controller_spec.rb:12:in `block (3 levels) in <top (required)>'
4) Vote after_save calls `Post#update_rank` after save
Failure/Error: vote = Vote.new(value: 1, post: post)
NameError:
undefined local variable or method `post' for #<RSpec::ExampleGroups::Vote::AfterSave:0x007fdabdb8b0b0>
# ./spec/models/vote_spec.rb:25:in `block (3 levels) in <top (required)>'
Finished in 0.78639 seconds (files took 2.82 seconds to load)
15 examples, 4 failures, 2 pending
Failed examples:
rspec ./spec/controllers/favorites_controller_spec.rb:14 # FavoritesController#create creates a favorite for the current user and specified post
rspec ./spec/controllers/favorites_controller_spec.rb:24 # FavoritesController#destroy destroys the favorite for the current user and post
rspec ./spec/controllers/votes_controller_spec.rb:8 # VotesController#up_vote adds an up-vote to the post
rspec ./spec/models/vote_spec.rb:24 # Vote after_save calls `Post#update_rank` after save
This is the favorites_controller_spec.rb file:
require 'rails_helper'
describe FavoritesController do
include Devise::TestHelpers
before do
#post = create(:post)
#user = create(:user)
sign_in #user
end
describe '#create' do
it "creates a favorite for the current user and specified post" do
expect( #user.favorites.find_by(post_id: #post.id) ).to be_nil
post :create, { post_id: #post.id }
expect( #user.favorites.find_by(post_id: #post.id) ).not_to be_nil
end
end
describe '#destroy' do
it "destroys the favorite for the current user and post" do
favorite = #user.favorites.where(post: #post).create
expect( #user.favorites.find_by(post_id: #post.id) ).not_to be_nil
delete :destroy, { post_id: #post.id, id: favorite.id }
expect( #user.favorites.find_by(post_id: #post.id) ).to be_nil
end
end
end
and this is the votes_controller_spec.rb file:
require 'rails_helper'
describe VotesController do
include TestFactories
describe '#up_vote' do
it "adds an up-vote to the post" do
request.env["HTTP_REFERER"] = '/'
#user = authenticated_user
#post = associated_post
sign_in #user
expect {
post( :up_vote, post_id: #post.id )
}.to change{ #post.up_votes }.by 1
end
end
end
Check if you have config.include FactoryGirl::Syntax::Methods inside rails_helper.rb
If you have above line in rails_helper.rb file you can always use FactoryGirl.create :user
You didn't probably include include Devise::TestHelpers in specs for VotesController that's why it does not see sign_in method
I was doing the RSpec testing with Rails and it's failing due to the namespaced model that I assigned to its associations of the model.
CLI:
Failures:
1) Blog::BlobsController GET index assigns all blog/blobs as #blobs
Failure/Error: expect(assigns(:blog::blobs)).to eq([blog::blobs])
NoMethodError:
undefined method `blobs' for :blog:Symbol
# ./spec/controllers/blog/blobs_controller_spec.rb:8:in `block (3 levels) in <top (required)>'
spec/controllers/blog/blobs_controller_spec.rb
RSpec.describe Blog::BlobsController, type: :controller do
describe "GET index" do
it "assigns all blog/blobs as #blobs" do
blobs = Blog::Blob.create!
get :index, {}
expect(assigns(:blog::blobs)).to eq([blog::blobs])
end
end
end
routes.rb
# SNIPPED FOR BREVITY...
namespace :blog do
resources :blobs
end
app/controllers/blog/blobs_controller.rb
class Blog::BlobsController < ApplicationController
before_filter :authenticate_user!, except: [:index, :show]
def index
#blobs = Blog::Blob.all
end
def new
#blob = Blog::Blob.new
end
def edit
#blob = Blog::Blob.find(params[:id])
end
def create
#blob = Blog::Blob.new(blob_params)
if #blob.save
redirect_to #blob
else
render 'new'
end
end
def update
#blob = Blog::Blob.find(params[:id])
if #blob.update(blob_params)
redirect_to #blob
else
render 'edit'
end
end
def show
#blob = Blog::Blob.find(params[:id])
end
def destroy
#blob = Blog::Blob.find(params[:id])
#blob.destroy!
redirect_to blog_blobs_path
end
private
def blob_params
params.require(:blob).permit(:title, :body)
end
end
Is there a better way to test this controller with RSpec?
UPDATE:
Failures:
1) Blog::BlobsController GET #index assigns all widgets as #widgets
Failure/Error: expect(assigns(:blobs)).to eq([blob])
TypeError:
no implicit conversion of Symbol into Integer
# /usr/local/rvm/gems/ruby-2.1.5#rails4/gems/mongo-2.0.4/lib/mongo/server_selector.rb:56:in `[]'
# /usr/local/rvm/gems/ruby-2.1.5#rails4/gems/mongo-2.0.4/lib/mongo/server_selector.rb:56:in `get'
# /usr/local/rvm/gems/ruby-2.1.5#rails4/gems/mongo-2.0.4/lib/mongo/client.rb:170:in `read_preference'
# /usr/local/rvm/gems/ruby-2.1.5#rails4/gems/mongo-2.0.4/lib/mongo/collection/view/readable.rb:318:in `default_read'
# /usr/local/rvm/gems/ruby-2.1.5#rails4/gems/mongo-2.0.4/lib/mongo/collection/view/readable.rb:251:in `read'
# /usr/local/rvm/gems/ruby-2.1.5#rails4/gems/mongo-2.0.4/lib/mongo/collection/view/iterable.rb:38:in `each'
# /usr/local/rvm/gems/ruby-2.1.5#rails4/bundler/gems/mongoid-26f67146a7b7/lib/mongoid/query_cache.rb:207:in `each'
# /usr/local/rvm/gems/ruby-2.1.5#rails4/bundler/gems/mongoid-26f67146a7b7/lib/mongoid/contextual/mongo.rb:116:in `each'
# /usr/local/rvm/gems/ruby-2.1.5#rails4/bundler/gems/mongoid-26f67146a7b7/lib/mongoid/contextual.rb:20:in `each'
# /usr/local/rvm/gems/ruby-2.1.5#rails4/bundler/gems/mongoid-26f67146a7b7/lib/mongoid/criteria.rb:48:in `entries'
# /usr/local/rvm/gems/ruby-2.1.5#rails4/bundler/gems/mongoid-26f67146a7b7/lib/mongoid/criteria.rb:48:in `=='
# ./spec/controllers/blog/blobs_controller_spec.rb:8:in `block (3 levels) in <top (required)>'
Updated spec code:
require 'rails_helper'
RSpec.describe Blog::BlobsController, type: :controller do
describe "GET #index" do
it "assigns all blobs as #blobs" do
blob = Blog::Blob.create!
get :index, {}
expect(assigns(:blobs)).to eq([blob])
end
end
end
Your test says:
blobs = Blog::Blob.create!
This is confusing, because blobs is plural, but you're only creating one blob. So start by renaming that to blob. Then expect(assigns(:blog::blobs)).to eq([blog::blobs]) should be expect(assigns(:blobs)).to eq([blob]).
In the index action, you set #blobs = Blog::Blob.all. The assigns correspond to the controller's instance variables. There's no namespacing.
I am following Michael Hartl's tutorial, and trying to implement the reply twitter-like functionality, ie. "#122-john-smith: hello there" should be a reply to user 122.
I first tried filtering the "#XXX-AAA-AAA" part using a before_filter, but I decided to try it first in the very same Micropost#create action. So far I've got this MicropostController:
class MicropostsController < ApplicationController
before_filter :signed_in_user, only: [:create, :destroy]
before_filter :correct_user, only: [:destroy]
#before_filter :reply_to_user, only: [:create]
def index
end
def create
#micropost=current_user.microposts.build(params[:micropost])
#Rails.logger.info "hoooola"
regex=/\A#(\d)+(\w|\-|\.)+/i
message=#micropost.content.dup
isResponse=message.match(regex)[0].match(/\d+/)[0]
#micropost.response=isResponse
if #micropost.save
flash[:success]="Micropost created!"
redirect_to root_path
else
#feed_items=[]
render 'static_pages/home'
end
end
def destroy
#micropost.destroy
redirect_to root_path
end
private
def correct_user
#micropost = current_user.microposts.find_by_id(params[:id])
redirect_to root_path if #micropost.nil?
end
def reply_to_user
regex=/\A#(\d)+(\w|\-|\.)+/i
#I use [0] cause the output of match is a MatchData class with lots of bs
mtch=params[:micropost][:content].match(regex)[0]
#puts mtch
##micropost=current_user.microposts.build(params[:micropost])
if mtch != nil
user_id=mtch.match(/\d+/)[0]
#replied_user=User.find(user_id)
#micropost.response=user_id unless #replied_user.nil?
end
end
end
And this is the snippet test I'm trying to pass:
require 'spec_helper'
describe "MicropostPages" do
subject { page }
let(:user) { FactoryGirl.create(:user) }
before { valid_signin user }
describe "micropost creation" do
before { visit root_path }
describe "with invalid information" do
it "should not create a micropost" do
expect { click_button "Post" }.should_not change(Micropost,
:count)
end
describe "error messages" do
before { click_button "Post" }
it { should have_content('error') }
end
end
describe "with valid information" do
before { fill_in 'micropost_content', with: "Lorem ipsum" }
it "should create a micropost" do
expect { click_button "Post" }.should change(Micropost,
:count).by(1)
end
end
end
...
end
If I run these tests I get the follwing error:
Failures:
1) MicropostPages micropost creation with invalid information should not create a micropost
Failure/Error: expect { click_button "Post" }.should_not change(Micropost, :count)
NoMethodError:
undefined method `[]' for nil:NilClass
# ./app/controllers/microposts_controller.rb:14:in `create'
# (eval):2:in `click_button'
# ./spec/requests/micropost_pages_spec.rb:11:in `block (5 levels) in <top (required)>'
# ./spec/requests/micropost_pages_spec.rb:11:in `block (4 levels) in <top (required)>'
2) MicropostPages micropost creation with invalid information error messages
Failure/Error: before { click_button "Post" }
NoMethodError:
undefined method `[]' for nil:NilClass
# ./app/controllers/microposts_controller.rb:14:in `create'
# (eval):2:in `click_button'
# ./spec/requests/micropost_pages_spec.rb:14:in `block (5 levels) in <top (required)>'
However if I modify the tests and comment out all the #XXX filtering in the Micropost#create action:
def create
#micropost=current_user.microposts.build(params[:micropost])
#Rails.logger.info "hoooola"
#regex=/\A#(\d)+(\w|\-|\.)+/i
#message=#micropost.content.dup
#isResponse=message.match(regex)[0].match(/\d+/)[0]
##micropost.response=isResponse
if #micropost.save
flash[:success]="Micropost created!"
redirect_to root_path
else
#feed_items=[]
render 'static_pages/home'
end
end
The tests pass just fine and the new Micropost is not a Nil object.
It can't seem to find an explanation here.
The error comes from this line:
isResponse=message.match(regex)[0].match(/\d+/)[0]
Check if your two match calls actually match correctly. If the pattern is not found in your string, nil is returned and the [0] call is made on nil. There's two instances in this line alone where this could happen.
Try to spread it out over several lines and check the return values of your matches or extend your Regex to properly check the pattern in one go.