Using log_in_as helper module in ActionDispatch::IntegrationTest - ruby-on-rails-4

I started learning Rails using Michael Hartl's "Ruby on Rails Tutorial", then I started to customize some classes to suit my own needs.
At this time, I have 2 main classes I can manage with my application:
"users": admin user can list, create destroy them
"apps": admin can list, create destroy them
I recycled most from the tutorial, and managed to make the application working for both of them.
"users" integration testing works fine.
When started to develop the "apps" testing, I found there is something that makes login fail and I'm really stucked on this.
Here is the "users" integration test (it works):
require 'test_helper'
class UsersCreateTest < ActionDispatch::IntegrationTest
fixtures :all
def setup
#admin = users(:admin)
end
test "user create with valid information" do
log_in_as(#admin)
assert is_logged_in?
get new_user_path()
...
assert_difference 'User.count', 1 do
post users_path, user:{ username: "newuser",
email: "user#example.com",
password: "pippo1",
password_confirmation: "pippo1",
...
}
follow_redirect!
end
...
end
end
Here is the test to create a new "app" (does not work):
require 'test_helper'
class AppsCreateTest < ActionDispatch::IntegrationTest
fixtures :all
def setup
#admin= users(:admin)
#app= apps(:app1)
end
test "create app with valid information" do
log_in_as(#admin)
assert is_logged_in?
get new_app_path()
...
assert_difference( 'App.count', 1) do
post apps_path, app: { appname: "newapp",
desc: "short descprition here",
...
}
follow_redirect!
end
end
end
Finally, here is the "test_helper.rb" part, which comes straight from the Hartl Tutorial:
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
def is_logged_in?
!session[:user_id].nil?
end
# Logs in a test user.
def log_in_as(user, options = {})
password= options[:password] || 'pippo1'
if integration_test?
post "/login", session: {
username: user.username,
password: password }
else
session[:user_id] = user.id
end
end
private
# Returns true inside an integration test.
def integration_test?
defined?(post_via_redirect)
end
end
The "app" test fails when it tries to do post operation in "log_in_as".
It seems that the "user" test inherits some method while the "app" test doesn't.
Any suggestion is appreciated.

Related

Ruby on Rails Pundit's current_user is nil in integration test

I'm using the gems pundit and devise. I have a delete link that only shows up if you are an admin. I have an integration test that I would like to verify that the delete link only shows up for admins.
test 'comment delete link shows when it should' do
log_in_as #admin
get movie_path(#movie)
assert_select 'a[href=?]', movie_comment_path(comments(:one), #movie.id)
end
My test_helper.rb looks like this:
...
class ActiveSupport::TestCase
...
def log_in_as(user, options = {})
password = options[:password] || 'password'
if integration_test?
post user_session_path, 'user[email]' => user.email, 'user[password]' => user.password
else
Devise::TestHelpers.sign_in user
end
end
private
# Returns true inside an integration test.
def integration_test?
defined?(post_via_redirect)
end
end
The response.body looks all right, but indeed there is no delete link. There is one when I run the development server and visit the page myself. I've narrowed this down to the current_user that pundit uses in the policies is being passed in with a value of nil. This is my comment_policy.rb:
class CommentPolicy
attr_reader :current_user, :comment
def initialize(current_user, model)
#current_user = current_user
#comment = model
end
def create?
if #current_user
#current_user.member? or #current_user.content_creator? or #current_user.moderator? or #current_user.admin?
end
end
def destroy?
if #current_user
#current_user == #comment.user or #current_user.moderator? or #current_user.admin?
end
end
end
As a closing remark, I've heard that Rails 5 has opted for integration tests instead of controller tests as we know them from Rails 4 for the default type of tests to be generated for our controllers. If this is the case, devise would be a heck of a lot more useful out of the box when using Rails 5 if the sign_in/sign_out helpers that work in controller tests were made to work in integration tests as well. But would I still have this issue of pundit not knowing what current_user is? I'm assuming this all works fine in controller tests because the current_user is scoped to controllers? Any and all light shed on this topic is much appreciated, but I would really like to figure out how to get integration tests to work with this setup because I have about a billion I want to write right now.
Not that it totally matters, but does it need to be using current_user in the policy or can it just use user in the policy. By this I mean according to the elabs/pundit README on Github I would just use #user and user everywhere instead of current_user. Read the README if I confused you.
Additionally the nil for current_user typically occurs when you don't have a valid CSRF token for your request. When you do this on the website manually by going to localhost:3000 or w/e you are first performing a get on the login path before doing the post on the login path with your credentials. In your integration test I don't seem to see where you are performing that get in order to get the CSRF for your session.
Hope this helps!!!

Rspec/Capybara: Devise user 'dissapears' after logging in

I'm having a bizarre problem where I create an admin user for an Rspec/Capybara test and the user is mysteriously deleted after logging in. When I run my test, the user is created and successfully logged in. However when Capybara visits the admin_categories_path, the test fails. Rails raises an exception because current_user is not defined. When I insert a binding.pry, I can see that the user exists up until they are logged in, at which point the user disappears from the test database, causing current_user to be undefined, and thereby triggering an exception. I'm at a loss as to how/why this is happening.
UPDATE: I've gotten past the problem of the user being deleted. Now when Capybara sees the admin_categories_path page, category isn't displayed. Inserting a binding.pry reveals that category is present in the database.
When I launch the app and log in manually, I have no problems accessing admin_categories_path.
Here is my spec file:
require 'rails_helper'
feature 'admin edits category', %Q{
As an admin, I want to edit a category or subcategory, so that it better
represents the content under it.
Acceptance Criteria:
* [X] - I can edit the name of a category inline.
* [X] - I can edit the name of a subcategory inline.
} do
let(:admin) do
FactoryGirl.create(:user, admin: true)
end
let(:category) do
FactoryGirl.create(:category)
end
scenario 'admin edits category title', js: true, focus: true do
login_as(admin)
visit admin_categories_path
bip_area category, :name, 'Test Category'
expect(page).to have_content 'Test Category'
end
end
Here is my helper file authentication.rd:
module Helpers
module Authentication
def log_in_as(user)
visit new_user_session_path
within "#new_user" do
fill_in 'user[email]', with: user.email
fill_in 'user[password]', with: user.password
click_on "Log in"
end
end
end
RSpec.configure do |config|
config.include Authentication, :type => :feature
end
end
Here is my user factory:
require 'factory_girl'
FactoryGirl.define do
factory :user do
sequence(:email) {|n| "lafiel.abriel#{n}#abhnation.com" }
username
password 'password'
password_confirmation 'password'
end
factory :category do
sequence(:name) { |n| "Category ##{n}" }
parent_id nil
display_index 1
user
end
sequence :username do |n|
"Lafiel_Abriel_#{n}"
end
end
And here is my application_controller.rd where the exception is triggered:
module Admin
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
before_action :reject_unless_admin
layout 'admin/layouts/application'
protect_from_forgery with: :exception
helper :avatar, :devise, :admin
protected
def reject_unless_admin
unless current_user && current_user.admin?
raise ActionController::RoutingError.new('404: Not Found')
end
end
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << [
:avatar,
:remote_avatar_url,
:email,
:username,
:first_name,
:last_name,
:age,
:website,
:password,
:password_confirmation,
:current_password
]
end
end
end
Any help/insight is greatly appreciated. Thanks.
If I recall correctly, this problem had something to do with the test database schema being out of sync with the development database. Try running rake db:test:prepare to ensure your test schema matches your development schema.
In my specific case, I had a two problems to overcome.
The first problem occurred when I created a category and an admin in a let block. Those needed to be placed in a before block so that they were created before the test executed. When I placed those variables in let blocks, they were not being created until the first time they were called in the test. So when I logged in as an admin, the admin variable was being passed to my login_as helper method before it was saved to the database. The same is true for the category variable.
This code doesn't work for me:
let(:admin) do
FactoryGirl.create(:user, admin: true)
end
let(:category) do
FactoryGirl.create(:category)
end
scenario 'admin edits category title', js: true, focus: true do
login_as(admin)
visit admin_categories_path
bip_area category, :name, 'Test Category'
expect(page).to have_content 'Test Category'
end
This is solution I used to overcome the first problem:
before(:each) do
#admin = FactoryGirl.create(:user, admin: true)
#category = FactoryGirl.create(:category, user: #admin)
end
scenario 'admin edits category title', js: true do
skip "Doesn't work yet."
login_as(#admin)
visit admin_categories_path
wait_for_ajax
bip_text #category, :name, 'Test Category'
expect(page).to have_content 'Test Category'
end
The second problem is that when my test hits the admin/categories_controller.rb, Category.all returns an empty array, even though #category.save! and #category.valid? return true when I test my before block. I was never able to find a solution to the problem and ended up putting the test on ice.
I think part of the problem is that the documentation for the Best-in-Place gem is not very good. I used it at the time because it was an easy solution to my problem. Going forward though, I would use something like angular for this use-case. The documentation is much better and it's not a black box like a lot of gems are.
I'm not sure what bip_area does, but since your test says that it's editing a category I assume you are expecting the category to be present on the page when you visit admin_categories_path. When you visit that path however category has not yet been created since you are using 'let' which is lazily evaluated (created at time of first use of the variable), so it would not be shown on the screen for you to edit. Using binding.pry and then looking at that variable would actually create it, so it might be confusing you into thinking it was there. You can use 'let!' instead which will force the variable to be created before each test instead of lazily evaluating it.

Rails 4 + Merit + Devise: set a badge for user after registration

I have a trouble at this situation. I followed this manual, but it don't helped me.
Here's my files:
routes.rb:
devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks', registrations: 'registrations' }
merit.rb:
Merit.setup do |config|
config.checks_on_each_request = true
end
Merit::Badge.create!(
id: 1,
name: 'just-registered',
description: 'Badge for register'
)
badge_rules.rb
module Merit
class BadgeRules
include Merit::BadgeRulesMethods
def initialize
grant_on 'registrations#create', badge: 'just-registered', model_name: 'User'
end
end
end
registrations_controller.rb
def create
#user = build_resource
super
end
And if make sense - when user is registered, to merit_actions table added a new record with target_model = 'registrations', not 'users'
Can someone tell me, what i'm doing wrong ?
That's expected behavior, merit_actions is internal to the gem and saves controller_path as it's target_model attribute. It is confusing, but it shouldn't affect your application. Is the badge being granted?

Strange Behaviour with .errors on Factory Girl Stubbed Object

I am using factory_girl_rails (4.2.1) and rspec-rails (2.14.0) to test a simple controller on Rails 4. When testing an error case, I use FactoryGirl.build to build an invalid User object. However, the resulting object does not contain any error in #user.errors; yet expect(assigns(:user)).to have(1).errors_on(:email) in the test case still passes. Why doesn't the FactoryGirl generated object has any error, and how does rspec see the error?
Here are the details and code.
The controller simply creates a User object, then redirect to a verification page if creation was successful or render the form again if there is any error.
class RegistrationController < ApplicationController
def new
end
def create
#user = User.create(params.required(:user).permit(:email, :password, :password_confirmation))
if #user.errors.empty?
redirect_to verify_registration_path
else
render :new
end
end
end
In my error case test, I create a User without 'email' using FactoryGirl. It is expected to create an error entry in #user.errors for the 'email' field AND renders the :new template.
describe RegistrationController do
#... Some other examples ...
describe 'GET create' do
def post_create(user_params)
allow(User).to receive(:create).with(ActionController::Parameters.new({user: user_params})[:user]).and_return(FactoryGirl.build(:user, user_params))
post :create, user: user_params
end
context 'without email' do
before { post_create email: '', password: 'testing', password_confirmation: 'testing' }
subject { assigns(:user) }
it 'build the User with error' do
expect(subject).to have(1).errors_on(:email)
end
it 'renders the registration form' do
expect(response).to render_template('new')
end
end
end
end
However, when I ran the test case, only the 'renders the registration form' example failed, but not the other one.
Failures:
1) RegistrationController GET create without email renders the registration form
Failure/Error: expect(response).to render_template('new')
expecting <"new"> but rendering with <[]>
# ./spec/controllers/registration_controller_spec.rb:51:in `block (4 levels) in <top (required)>'
Finished in 0.25726 seconds
6 examples, 1 failure
Failed examples:
rspec ./spec/controllers/registration_controller_spec.rb:50 # RegistrationController GET create without email renders the registration form
What is strange here is that rspec seems to be able to see an error in #user (hence the first test case passes) but for some unknown reason #user.error.empty? returns true in controller causing it to redirect instead of rendering the :new template (hence the failed second test case). I also confirmed in debugger that #user.error was indeed empty.
Is it something wrong with how FactoryGirl handles error, or am I using it wrong?
Thanks
Two things I want to mention here are:
1. Probably You want to use "Post create" instead of "Get create".
2. Whether email is missing or not is the model's concern, not controller's.
I suggest you use stub to return false for the case that email is missing.
The easiest way is:
User.any_instance.stub(:create).and_return(false)
And maybe you want to change some other things in the controller, like "if #user.errors.empty?"
EDIT: Sorry, "create" actually doesn't return false.
So in your controller
#user = User.new(.....)
if #user.save
...
else
render :new
And in your test use
User.any_instance.stub(:save).and_return(false)

how do you stub a local variable in an rspec controller test

I've just implemented OmniAuth (using Ryan Bates' Screencast http://asciicasts.com/episodes/235-omniauth-part-1) and am writing Rspec tests for the functionality and have ran into trouble testing the authentifications#create action. I'm at quite a loss as to how to test this one -- in particular how to stub the local variable omniauth. No matter what I try I keep can't get any tests to work.
Taking a cut down version of the action, how would you test that a new is called on User for example
#cut down version of the authentifications controller code I am attempting to test
def create
omniauth = request.env["omniauth.auth"]
authentification = Authentification.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
....
user = User.new
....
end
#example test
it "should create a new user" do
subject.stub_chain(:request,:env) {{"omniauth.auth" => {'provider' =>1, 'uid' => 2}}}
User.should_receive(:new)
post :create
end
I Did that :
class SessionsController < ApplicationController
def create
#user = User.find_by_auth_hash(auth_hash)
end
def auth_hash
request.env['omniauth.auth']
end
end
describe SessionsController do
it 'should allow login' do
controller.stub!(:auth_hash).and_return({'provider' => 'twitter', 'uid' => '1234'})
get :create, :provider => 'twitter'
assigns(:user).should_not be_nil
end
end
Hope that helps.