Im trying to test my successfully creates a new user after login (using authlogic). Ive added a couple of new fields to the user so just want to make sure that the user is saved properly.
The problem is despite creating a valid user factory, whenever i try to grab its attributes to post to the create method, password and password confirmation are being ommitted. I presuem this is a security method that authlogic performs in the background. This results in validations failing and the test failing.
Im wondering how do i get round this problem? I could just type the attributes out by hand but that doesnt seem very dry.
context "on POST to :create" do
context "on posting a valid user" do
setup do
#user = Factory.build(:user)
post :create, :user => #user.attributes
end
should "be valid" do
assert #user.valid?
end
should_redirect_to("users sentences index page") { sentences_path() }
should "add user to the db" do
assert User.find_by_username(#user.username)
end
end
##User factory
Factory.define :user do |f|
f.username {Factory.next(:username) }
f.email { Factory.next(:email)}
f.password_confirmation "password"
f.password "password"
f.native_language {|nl| nl.association(:language)}
f.second_language {|nl| nl.association(:language)}
end
You definitely can't read the password and password_confirmation from the User object. You will need to merge in the :password and :password_confirmation to the #user.attributes hash. If you store that hash somewhere common with the rest of your factory definitions, it is not super dry, but it is better than hardcoding it into your test.
Related
So I want to make sure this is possible and actually doable with what im trying to do.
I had previously been using a seeds.rb file to seed the database with test data, this worked for my Capybara integration tests but messed up some of the other unit tests which rely on a schema.rb file and Factories to create data.
Can I use a factory to create test data for that particular integration spec. Something like this for a factory:
FactoryGirl.define do
factory :user do
first_name Faker::Name.first_name
last_name Faker::Name.last_name
email Faker::Internet.email
password "password"
end
end
Then I have a super simple spec which logins to a site in Capybara:
it 'Check correct login' do
visit('/sign_in')
page.fill_in 'user_email', :with => 'test#test.com'
page.fill_in 'user_password', :with => 'p4ssw0rd'
click_button('Sign In')
end
This is hitting a Sqlite database, can I insert my factory and it will work using capybara? Im really not familiar with factorygirl, but is it actually creating data in the database and then just removing it?
I don't commonly see Capybara used with FactoryGirl in a lot of the examples I search online, is there a reason for that?
edit:
Here is what I have currently:
it 'Check correct login' do
user = FactoryGirl.create(:user)
visit('/d/users/sign_in')
page.fill_in 'user_email', :with => user.email
page.fill_in 'user_password', :with => user.password
click_button('Log In')
page.assert_text('Signed in successfully.')
end
I was able to take a screenshot and confirm that the forms are getting filled in with a random username/password, but using DB Browser for SQlite I don't seem to see the actual data in the database getting populated (Which might be difficult since once the spec is done it's deleted right?) but I can't tell if it's actually creating the data or not.
Thanks!
This should work fine w/o many hitches. You'll need to instantiate your User object in your test as this looks like a 'sign-in'.
You can create the object a couple of different ways.
(1)
describe 'Test' do
let(:user){ create :user }
...
it 'Specific Test' do
...
Note that let!(:user){...} creates immediately and let(:user){...} will only create user when the user is called. You will then be able to access user in all your tests.
(2)
describe 'Test' do
before do
#user = FactoryGirl.create( :user )
end
it 'Specific Test' do
...
Here you will be able to access #user in all your tests.
Let us know if that works and if not what error you're getting.
EDIT:
If your FG file looked like this:
FactoryGirl.define do
factory :user do
first_name Faker::Name.first_name
last_name Faker::Name.last_name
email Faker::Internet.email
password "password"
work
end
end
You could associate work like this:
let(:user){ create :user, work: 'Some Place' }
#user = FactoryGirl.create(:user, work: 'Some Place')
I was looking at this answer to see how to test a session controller and wrote something like this:
require 'spec_helper'
describe SessionsController do
context "We should login to the system and create a session" do
let :credentials do
{:user_name => "MyString", :password => "someSimpleP{ass}"}
end
let :user do
FactoryGirl.create(:user, credentials)
end
before :each do
post :create , credentials
end
it "should create a session" do
puts user.inspect
puts session[:user_id]
#session[:user_id].should == user.id
end
end
end
Based on that I created a factory girl user:
FactoryGirl.define do
factory :user, :class => 'User' do
name "sample_user"
email "MyString#gmail.com"
user_name "MyString"
password "someSimpleP{ass}"
end
end
Now it all works - exceot for the before :each do statement - it never "logs" the "user" in - thus I cannot test the controllers functionality of, is a session properly created?
Now most would say, use capybara and test it through that way - but that's wrong, IMO - sure if I'm doing front end testing that would work, but I'm testing controller based logic. Can some one tell me why this isn't working? routing works fine.
My puts session[:user_id] is coming up nil, when it shouldn't
let is lazily evaluated, even for the before clause, so the user has not been created as of the time you do the post to login. If you change to using let!, you'll avoid this problem.
You misunderstood SessionsController and RegistrationsController.
A Session is for an user who has already registered, not for creating an user. #create in SessionController means to create a session, not an user.
RegistrationController is for creating user with full details including password_confirmation.
To test SessionsController, you need to create a valid user in FactoryGirl at first, then use his credentials say email and password to sign in.
I've been trying to get a grasp on writing tests, but having a lot of trouble as the tests never seem to validate the way I want them to. In particular, I've been trying to use Factory Girl as opposed to fixtures - as suggested by a recent Railscasts and other advice I've seen on the net - due to the benefits it professes, and that hasn't worked out.
For example, here is a simple Rspec test for a user model, testing to make sure a username is present...
describe User do
it "should not be valid without a username" do
user = FactoryGirl.create(:user, :username => "", :password => "secret")
user.should_not be_valid
end
end
And my factories.rb file, if it helps...
FactoryGirl.define do
factory :user do
sequence(:username) { |n| "registered-#{n}" }
password "foobar"
end
end
When I run 'rake spec,' it tells me...
1) User should not be valid without a username
Failure/Error: user = FactoryGirl.create(:user, :username => "", :password => "secret")
ActiveRecord::RecordInvalid:
Validation failed: Username can't be blank
Ummm...that's the POINT. If I specified that the user should NOT be valid, shouldn't this test actually pass?
If I replace the Factory Girl line and set the user in the test with something like 'user = User.new(:username => "", :password => "secret")', to no surprise the test passes fine. So why is Factory Girl not working right?
You should use build like in the following:
user = Factory.build(:user, :username=>"foo")
Because using the method you're using will try to create a record. See docs for further information.
I have a User model and Authentications model, which is a basic omniauth setup. Essentially, users can sign up through oauth without setting a password.
I have a Authentication.is_destroyable? method that returns true if the user has a password or has more than one authentication. Essentially, this prevents users deleting their one and only way of authentication.
def is_destroyable?
if user.encrypted_password.present? || user.authentications.count > 1
true
else
errors.add :base, 'not allowed'
false
end
end
When testing this in development it works as expected under all conditions. However, my unit tests are failing:
describe "Authentication#is_destroyable?" do
before(:each) do
# This creates a user with no password and a single authentication
#user = FactoryGirl.create(:user_with_oauth)
#auth = #user.authentications.first
end
# This spec passes :)
it "should return false when is users only authentication method" do
#auth.is_destroyable?.should be_false
end
# This FAILS - I have no idea why :(
it "should return true when user has multiple authentications" do
#user.authentications.create FactoryGirl.attributes_for(:authentication, :provider => 'twitter')
#auth.is_destroyable?.should be_true
end
# This FAILS - I have no idea why :(
it "should return true when user has a password" do
#user.update_attributes :password => 'password'
#auth.is_destroyable?.should be_true
end
end
I've spent the best part of 3 hours banging my head against the wall. I can't for the life of me understand why this works when I manually test the functionality (and Cucumber stories pass also testing the functionality), but in rspec the unit tests are failing. Is there something obvious that I'm missing?
Edit
As requested, here's some further detail.
Both failing specs fail with:
Failure/Error: #auth.is_destroyable?.should be_true
expected false to be true
The Factories:
FactoryGirl.define do
factory :user do
username { FactoryGirl.generate(:username) }
name 'Test User'
email { FactoryGirl.generate(:email) }
password 'password'
end
factory :user_with_oauth, :parent => :user do
password nil
authentications [ FactoryGirl.build(:authentication) ]
end
factory :authentication do
provider 'facebook'
uid SecureRandom.hex(16)
end
end
Also, maybe relevant, am using DatabaseCleaner with the truncation strategy.
I can answer my own question (after 2 more hours of hitting my head against the wall)...
My :user_with_oath Factory was to blame; I wasn't wrapping the authentications association in a block:
factory :user_with_oauth, :parent => :user do
password nil
authentications { [FactoryGirl.build(:authentication)] }
end
I'm trying to test a case in our Ruby on Rails system where we lock a user out after x failed login attempts. The issue I'm having is trying to create a user has reached the number that 'locks' his account. I am using Factories to create a user like so-
Factory.define :locked_user, :class => User do |user|
user.name "Test Lock"
user.email "lock#lock.com"
user.password "blah1234"
user.password_confirmation "blah1234"
user.login_count 5
end
Where 5 is the 'magic number'. When I try to use something like
#user = Factory(:locked_user)
It creates a user in the database- but newly created users always have login_count set to zero, so it just logs him in the test. When I try the .build method like so
#user = Factory.build(:locked_user)
It sets a user with login_count = 5 like I want, but then doesn't see the user as valid and won't try to log them in (ie, it gives us the 'bad user/password' error rather then 'right user/password but you are locked out' error). I guess I'm missing something here to get RSpec to pick up the fact that this is valid user but the account should be locked. Can someone help set me straight? Below is the entire desribe block-
describe "with locked account" do
before(:each) do
#user = Factory.build(:locked_user)
#attr = { :email => #user.email, :password => #user.password}
end
it "should not allow signin with locked account" do
post :create, :session => #attr
flash.now[:error].should =~ /Invalid user locked out/i
end
end
I would recommend you either set the login_count after creating the user, or stub the method that tells you if a user login is locked.
For instance, use update_attribute to force the login_count after the user has been created:
before(:each) do
#user = Factory(:user)
#user.update_attribute(:login_count, 5)
#attr = { :email => #user.email, :password => #user.password}
end
Or use stubs to stub out the locked_login?, or equivalent method:
before(:each) do
#user = Factory(:user)
#user.stub(:locked_login?).and_return(true)
#attr = { :email => #user.email, :password => #user.password}
end