Cameron Bass Cameron Bass - 7 months ago 16
Ruby Question

RSpec - FactoryGirl sign in

I'm brand new to factory girl and pretty new to RSpec in general. I'm trying to set a sign in for the user as a factory. I thought this would be a good intro to Factories. I think I set the factory right but now I need to know how to implement it in the actual test. Ill show the test I've written thus far and maybe I can get some guidance through.

Here is factory:

FactoryGirl.define do
factory :user do

email "cam@example.com"
password "password"

end
end


here is the feature test:

require "rails_helper"

RSpec.feature "Send a message" do
scenario "Staff can send a message" do
visit "/"

group = Group.create!(name: "Group A")
user = User.create!(email: "staff@example.com", password: "password")
fill_in "Email", with: "staff@example.com"
fill_in "Password", with: "password"
click_button "Sign in"

person = Person.create!(groups: [group], phone_number: "+161655555555")
message = Message.create(body: "Test Message", group_ids: [group.id])
fill_in "Enter a Message:", with: "Test Message"
check "message_group_#{group.id}"
click_button "Send Message"

expect(page).to have_content("Messages on their way!")
expect(page).to_not have_content("Body can't be blank")
expect(page).to_not have_content("Group ids can't be blank")
end
end


I basically want to make a factory out of this chunk. That way I will not have to repeat this code over and over again right?

group = Group.create!(name: "Group A")
user = User.create!(email: "staff@example.com", password: "password")
fill_in "Email", with: "staff@example.com"
fill_in "Password", with: "password"
click_button "Sign in"

Answer

Factories are meant to create data, not execute a series of steps. What you want is a function to do this for you.

Something akin to this:

def sign_in
  visit "/"

  group = Group.create!(name: "Group A")
  user = FactoryGirl.create(:user)
  fill_in "Email", with: user.email
  fill_in "Password", with: user.password
  click_button "Sign in"
end

In your test

scenario "Staff can send a message" do
  sign_in

  # Rest of code
end

Or

before(:each) { sign_in }

scenario "Staff can send a message" do
  # Rest  of code
end

You can define this function in this file, in your spec_helper / rails_helper or within a file in spec/support/