Search code examples
ruby-on-railscapybararspec-rails

Rspec features macro wont work


I created a macro for my create_post_spec.rb rails v-5.2 ruby v-2.5.1 capybara v-3.2'

my macro

spec/support/features/session.rb

module Features

  def sign_in(user)
    visit new_user_session_path
    fill_in "Email", with: user.email
    fill_in "Password", with: user.password
    click_on "Log in"
  end
  
end

then include in my rails_helper

Rspec.confifure do |config|
 config.include Feature, type: feature
end

in my

spec/feature/create_post_spec.rb

require "rails_helper"

RSpec.describe "Create post" do

let(:user){ User.create(email: "example@mail.com", password: "password",
                     password_confirmation: "password")} 

  scenario "successfuly creating post" do    
    sign_in user
    visit root_path
    click_on "Create post"
    fill_in "Title", with: "Awesome title"
    fill_in "Body", with: "My rspec test"
    click_on "Publish"
    expect(page).to have_current_path root_path
  end

  scenario "unsuccessful creating post" do
    sign_in user
    visit root_path
    click_on "Create post"
    fill_in "Title", with: "Awesome title"
    fill_in "Body", with: ""
    click_on "Publish"
    expect(page).to have_css ".error"  
  end

  scenario "non-logged in user cant create post" do
  
  end

end

i get an undefined method sign_in, But if i use "feature" in my block

RSpec.feature "Create post....." do

it works

i wonder why it won't work if i use "describe"

RSpec.describe "Create post....." do

Solution

  • The difference between RSpec.feature and Rspec.describe is that RSpec.feature adds type: :feature and capybara_feature: true metadata to the block. The important thing there is the type: :feature metadata since it's what you're using to trigger the include of your module. You can use describe by adding your own metadata

    RSpec.describe "Create post", type: :feature do
      ...
    end
    

    or you can have RSpec automatically add the type based on the directory the spec file is in by changing the file directory to spec/features/xxx.rb (note the plural features) and ensuring

    RSpec.configure.do |config|
      config.infer_spec_type_from_file_location!
    end
    

    is enabled in your rails_helper - see https://relishapp.com/rspec/rspec-rails/docs/directory-structure