首页 > 解决方案 > Rspec 功能宏不起作用

问题描述

我为我的 create_post_spec.rb rails v-5.2 ruby​​ v-2.5.1 capybara v-3.2' 创建了一个宏

我的宏

规范/支持/功能/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

然后包含在我的 rails_helper 中

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

在我的

规格/功能/create_post_spec.rb

require "rails_helper"

RSpec.describe“创建帖子”做

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

我得到一个未定义的方法sign_in,但是如果我在我的块中使用“功能”

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

有用

我想知道如果我使用“描述”它为什么不起作用

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

标签: ruby-on-railscapybararspec-rails

解决方案


RSpec.feature和之间的区别在于Rspec.describeRSpec.feature元数据添加type: :featurecapybara_feature: true块中。重要的是type: :feature元数据,因为它是您用来触发模块包含的东西。您可以describe通过添加自己的元数据来使用

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

或者您可以通过将文件目录更改为spec/features/xxx.rb(注意复数features)并确保RSpec 根据 spec 文件所在的目录自动添加类型

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

在您的 rails_helper 中启用 - 请参阅https://relishapp.com/rspec/rspec-rails/docs/directory-structure


推荐阅读