Reputation: 63657
I want to test my Users#show controller. How can I use FactoryGirl to create test data to be passed into my controller?
In "spec/controllers/users_controller_spec.rb":
describe UsersController do
describe "GET #show" do
it "assigns the requested user to @user" do
user = Factory(:user) # How do I do this using FactoryGirl?
get :show, id: user
assigns(:user).should eq(user)
end
end
end
In "spec/factories/users.rb"
require 'faker'
FactoryGirl.define do
factory :user do
email { Faker::Internet.email }
end
# Replace email with nil. Apparently all other attributes defer to the
# original :user factory.
factory :invalid_user do
email nil
end
end
Upvotes: 0
Views: 1058
Reputation: 2656
To wrap things up:
Use create(:user)
or build(:user)
as shown in latest docs instead of Factory(:user)
.
build(:user)
does not save the object to database therefore you will probably have to stub controller's queries. It's faster though.
To pass the id of not persisted user you'll have to do get :show, id: user.id
instead of get :show, id: user
Upvotes: 2