Rspec how to avoid allow_any_instance_of - ruby-on-rails

Because of rubocop error I want to avoid using allow_any_instance_of in my specs.
I'm trying to change this one:
before do
allow_any_instance_of(ApplicationController).to receive(:maintenance_mode_active?).and_return(false)
end
it 'returns http success' do
expect(response).to have_http_status(:success)
end
According to the rubocop-docs it should be like:
let(:maintenance_mode?) { instance_double(ApplicationController) }
before do
allow(ApplicationController).to receive(:maintenance_mode_active?).and_return(false)
allow(maintenance_mode?).to receive(:maintenance_mode_active?)
end
it 'returns http success' do
expect(response).to have_http_status(:success)
end
Class which I want to test:
private
def check_maintenance?
if maintenance_mode_active? == true
redirect_to maintenance_mode
elsif request.fullpath.include?(maintenance_mode_path)
redirect_to :root
end
end
def maintenance_mode_active?
# do sth ...
mode.active?
end
With code above I've got an error:
2.1) Failure/Error: allow(ApplicationController).to receive(maintenance_mode?).and_return(false)
#<InstanceDouble(ApplicationController) (anonymous)> received unexpected message :to_sym with (no args)
# ./spec/controllers/static_pages_controller_spec.rb:15:in `block (4 levels) in <top (required)>'
2.2) Failure/Error: allow(ApplicationController).to receive(maintenance_mode?).and_return(false)
TypeError:
[#<RSpec::Mocks::MockExpectationError: #<InstanceDouble(ApplicationController) (anonymous)> received unexpected message :to_sym with (no args)>] is not a symbol nor a string
# ./spec/controllers/static_pages_controller_spec.rb:15:in `block (4 levels) in <top (required)>'

You must stub ApplicationController to return the instance_double(ApplicationController):
let(:application_controller) { instance_double(ApplicationController) }
allow(ApplicationController).to receive(:new).and_return(application_controller)
allow(application_controller).to receive(:maintenance_mode_active?).and_return(false)

Related

How correct test anonymous controller if request action set in block subject

I test resource controller. For this I created in test anonymous controller.
I have following rspec test:
describe '#destroy' do
before { allow(controller).to receive(:custom_actions_path).and_return('/') }
subject { delete :destroy, params: { id: post.id, locale: user.language }}
it 'delete resource' do
expect { Post }.to change(Post, :count).by(-1)
end
it 'instant variables are exist' do
assigns(:resource).should_not be_nil
end
it { expect(response).to redirect_to('/') }
it { expect(response.code).to eq '302' }
end
end
Tests always falls:
1) ResourceController::Crudify#destroy delete resource
Failure/Error: expect { Post }.to change(Post, :count).by(-1)
expected `Post.count` to have changed by -1, but was changed by 0
# ./spec/unit/controllers/concerns/resource_controller/crudify_spec.rb:162:in `block (3 levels) in <top (required)>'
# ./spec/rails_helper.rb:47:in `block (3 levels) in <top (required)>'
# ./spec/rails_helper.rb:46:in `block (2 levels) in <top (required)>'
2) ResourceController::Crudify#destroy instant variables are exist
Failure/Error: assigns(:resource).should_not be_nil
expected: not nil
got: nil
How correct test method destroy if request to action destroy i pass in block subject? Thank you
In some cases you should call subject explicitly. Mind the first example: it should be passed to the block so RSpec can actually evaluate before and after states.
describe '#destroy' do
before { allow(controller).to receive(:custom_actions_path).and_return('/') }
subject { delete :destroy, params: { id: post.id, locale: user.language }}
it 'deletes resource' do
expect { subject }.to change(Post, :count).by(1)
end
end

undefined method `header` in RSpec

To learn API by using Rails I'm reading this tutorial.
In a part of RSpec test there is a method like this:
spec/support/authentication_helper.rb
module AuthenticationHelper
def sign_in(user)
header('Authorization', "Token token=\"#{user.authentication_token}\", email=\"#{user.email}\"")
end
def create_and_sign_in_user
user = FactoryGirl.create(:user)
sign_in(user)
user
end
alias_method :create_and_sign_in_another_user, :create_and_sign_in_user
end
RSpec.configure do |config|
config.include AuthenticationHelper, type: :api
end
And the test failed by undefined method `header'.
Where is this header method defined?
This is the whole source code of this tutorial.
https://github.com/vasilakisfil/rails_tutorial_api/
spec/apis/users_spec.rb
require 'rails_helper'
describe Api::V1::UsersController, type: :api do
context :show do
before do
create_and_sign_in_user
#user = FactoryGirl.create(:user)
get api_v1_user_path(#user.id), format: :json
end
it 'returns the correct status' do
expect(last_response.status).to eql(200)
end
it 'returns the data in the body' do
body = HashWithIndifferentAccess.new(MultiJson.load(last_response.body))
expect(body[:user][:name]).to eql(#user.name)
expect(body[:user][:updated_at]).to eql(#user.updated_at.iso8601)
end
end
end
StackTrace
1) Api::V1::UsersController show returns the correct status
Failure/Error: create_and_sign_in_user
NameError:
undefined local variable or method `request' for #<RSpec::ExampleGroups::ApiV1UsersController::Show:0x007fcbfec91d60>
# ./spec/support/authentication_helper.rb:4:in `sign_in'
# ./spec/support/authentication_helper.rb:9:in `create_and_sign_in_user'
# ./spec/apis/user_spec.rb:6:in `block (3 levels) in <top (required)>'
# ./spec/rails_helper.rb:39:in `block (3 levels) in <top (required)>'
# ./spec/rails_helper.rb:38:in `block (2 levels) in <top (required)>'
# -e:1:in `<main>'
2) Api::V1::UsersController show returns the data in the body
Failure/Error: create_and_sign_in_user
NameError:
undefined local variable or method `request' for #<RSpec::ExampleGroups::ApiV1UsersController::Show:0x007fcbfb7cfa28>
# ./spec/support/authentication_helper.rb:4:in `sign_in'
# ./spec/support/authentication_helper.rb:9:in `create_and_sign_in_user'
# ./spec/apis/user_spec.rb:6:in `block (3 levels) in <top (required)>'
# ./spec/rails_helper.rb:39:in `block (3 levels) in <top (required)>'
# ./spec/rails_helper.rb:38:in `block (2 levels) in <top (required)>'
# -e:1:in `<main>'
I had to add api_helper.rb to use the methods.
module ApiHelper
include Rack::Test::Methods
def app
Rails.application
end
end
RSpec.configure do |config|
config.include ApiHelper, type: :api #apply to all spec for apis folder
config.include Rails.application.routes.url_helpers, type: :api
end
Here is source code in Github.
https://github.com/vasilakisfil/rails_tutorial_api/blob/008af67e88897a5bcde714ce13d39a26ec70fba7/spec/support/api_helper.rb
In spec/support/auth_helpers.rb, you can try something like this
module AuthHelpers
def authenticate_with_user(user)
request.headers['Authorization'] = "Token token=#{user.token}, email=#{user.email}"
end
def clear_authentication_token
request.headers['Authorization'] = nil
end
end
In Rspec's spec/rails_helper.rb
Rspec.configure do |config|
config.include AuthHelpers, file_path: /spec\/apis/
end
An example test in spec/apis/users_controller_spec.rb:
require 'rails_helper'
describe Api::V1::UsersController, type: :controller do
let(:user) { create(:user) }
context 'signed in' do
before do
authenticate_with_user user
end
it 'does something' # tests here
end
end
Hope it helps!
Edit: Note the type: :controller is important

NoMethodError: in Rspec

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

FactoryGirl::InvalidFactoryError Controller Spec

I'm trying to create a controller spec for a contact form. All I want is to test that the :new template is rendered when invalid attributes are submitted. I've tried various configurations of the factory, as well as changing it to a trait, instead of factory to no avail. The error message doesn't get very specific, just Invalid Factory. Any ideas would be appreciated!
# blog_app/spec/factories/inquiries.rb
FactoryGirl.define do
factory :inquiry do
name "TestName"
email "test#test.com"
phone "123-456-7890"
message "TestMessage"
end
factory :invalid_inquiry, parent: :inquiry do
name nil
end
end
#/app/controllers/inquiries_controller.rb
class InquiriesController < ApplicationController
def new
#inquiry = Inquiry.new
end
def create
#inquiry = Inquiry.new(params[:inquiry])
if #inquiry.deliver
render :thank_you
else
render :new
end
end
end
# spec/controllers/inquiries_controller_spec.rb
require 'spec_helper'
describe InquiriesController do
it "has a valid factory" do
FactoryGirl.build(:inquiry).should be_valid
end
describe "POST #create" do
context "with valid attributes" do
it "delivers inquiry" #pending
it "renders the :thank_you page template" do
post :create, inquiry: FactoryGirl.attributes_for(:inquiry)
response.should render_template :thank_you
end
end
context "with invalid attributes" do
it "does not deliver inquiry" do #pending
it "renders :new page template" do
post :create, inquiry: FactoryGirl.attributes_for(:invalid_inquiry)
response.should render_template :new
end
end
end
describe "GET #new" do
it "renders :new page template" do
get :new
response.should render_template :new
end
end
end
Finished in 0.31244 seconds
0 examples, 0 failures
/Users/.../.rvm/gems/ruby-2.0.0-p353/gems/factory_girl-4.4.0/lib/factory_girl.rb:73:in `lint': The following factories are invalid: (FactoryGirl::InvalidFactoryError)
* invalid_inquiry
from /Users/.../Documents/blog_app/spec/support/factory_girl.rb:8:in `block (2 levels) in <top (required)>'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:21:in `instance_eval'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:21:in `run'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:66:in `block in run'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:66:in `each'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:66:in `run'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:418:in `run_hook'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:27:in `block in run'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/reporter.rb:34:in `report'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:25:in `run'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:80:in `run'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:17:in `block in autorun'
Does this work?
FactoryGirl.define do
factory :inquiry do
name "TestName"
email "test#test.com"
phone "123-456-7890"
message "TestMessage"
factory :invalid_inquiry do
name nil
end
end
end
Alternatively you might try replacing:
post :create, inquiry: FactoryGirl.attributes_for(:invalid_inquiry)
with:
post :create, inquiry: FactoryGirl.attributes_for(:inquiry, name: nil)
and getting rid of the invalid_inquiry factory altogether.

Pre-processing within a Rails Controller create method does not work

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.

Resources