I am really new to the unit testing and i am trying to wrap my head around it. So the situation I have an article form where user can enter title and description and on clicking Create Article article should get created but only a logged in user can perform this operation so I need to test this.
Since I am new to this so this is what I am thinking,
- I will create a user first
- Save it to session as thats how the system checks if the user is logged in (but then i am also thinking its not a browser so this logic might not work), then how do i submit a form as a logged in user?
here is my try
require 'rails_helper'
RSpec.feature 'adding article' do
scenario 'allow user to add an article' do
@user = User.create(:email => "[email protected]", :password => 'password', :username => 'saadia1')
session[:user_id] = @user.id
visit new_article_path
# @article = Article.user.to eql(@user = User.find_by(id: 6))
fill_in "Title", with: "My Title"
fill_in "Description", with: "My description"
click_on("Create Article")
expect(page).to have_content("My Title")
expect(page).to have_content("My description")
end
end
When i run the command rspec spec/features/add_article_spec.rb
I see
Failures:
1) adding article allow user to add an article Failure/Error: session[:user_id] = @user.id
NameError: undefined local variable or method `session' for #<RSpec::ExampleGroups::AddingArticle:0x007f89285e32e8> # ./spec/features/add_article_spec.rb:6:in `block (2 levels) in <top (required)>'Finished in 0.0197 seconds (files took 1.35 seconds to load) 1 example, 1 failure
Failed examples:
rspec ./spec/features/add_article_spec.rb:4 # adding article allow user to add an article
So my question is how do i add an article as a logged in user? I will really appreciate any help on this.