2
votes

I am using Rspec, FactoryGirl and Spork for my tests.There are 2 things I am a litte unclear on, first is the location of my factories.rb file. At present I have it located in

spec/support/factories.rb

And it looks like this

 FactoryGirl.define do
 factory :user do
 email                 "[email protected]"
 password              "password"
 password_confirmation "password"
 confirmed_at           Time.now

 end 
 end

Within my spec_helper I have

config.include FactoryGirl::Syntax::Methods

Secondly I want to login a user before starting my tests for a controller , this particular controller has a before filter :authenticate_user!

I am using devise for my authentication so have added

config.include Devise::TestHelpers, :type => :controller

Reading the devise docs you can add a controller_macros.rb and specify methods like so to use

 def login_user
 before(:each) do
  @request.env["devise.mapping"] = Devise.mappings[:user]
  user = FactoryGirl.create(:user)
  user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are      using the confirmable module
  sign_in user
  end
  end

And so i added this also to my spec_helper

config.include ControllerMacros, :type => :controller

So when I add login_user before my controller tests i get undefined method login_user. Am i using two tools here to do the same thing? Do I actually need the devise methods or can it all be done with factoryGirl. If so how do i setup the login process before i can test a controller?

1

1 Answers

2
votes

Factories location should be in spec/factories. Check out this example app https://github.com/RailsApps/rails3-devise-rspec-cucumber/tree/master/spec.

For login, generally you seems to doing it right. Check the example app again and here: https://github.com/plataformatec/devise/wiki/How-To:-Controllers-and-Views-tests-with-Rails-3-%28and-rspec%29

For the undefined method login_user error be sure to have

Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

and

config.extend ControllerMacros, :type => :controller

in spec_helper. Devise methods should be available wtih subject:

subject.current_user.should_not be_nil