如何向 Rails 中的功能规范添加请求方法?

Dan*_*arp 5 rspec ruby-on-rails

我有一个简单的测试功能,称为test_feature_spec.rb

(这只是为了解决这个问题......实际规格要长得多,实际功能规格)

require "features_helper"

RSpec.feature "Simple Feature", type: :feature do
  scenario "a test scenario" do
    get "/"
  end
end
Run Code Online (Sandbox Code Playgroud)

我可以做各种 Rails-y 的事情,包括水豚驱动的事情(比如visit such_n_such_path)。然而上面的崩溃:

Failures:

  1) Simple Feature a test scenario
     Failure/Error: get "/"

     NoMethodError:
       undefined method `get' for #<RSpec::ExampleGroups::SimpleFeature:0x000000011a799788>
       Did you mean?  gets
                      gem
Run Code Online (Sandbox Code Playgroud)

如果我只是将其更改为type: :feature它就type: :request可以正常工作:

> rspec spec/features/test_feature_spec.rb
.

Finished in 0.64913 seconds (files took 5.82 seconds to load)
1 example, 0 failures
Run Code Online (Sandbox Code Playgroud)

似乎使用type=> Rails 或 Rspec 加载一些东西以允许调用控制器路由,但使用=>request则不然。typefeature

有没有办法加载这些辅助方法(例如get等等post),但仍然保留该功能type: :feature

我知道我可以将其更改为,type: :request但从技术上讲,这些是功能规范,即使对于其中一些人来说,为了设置某种状态或执行任何操作,他们需要调用某些 URL。

Dan*_*arp 2

看起来有一个有效的解决方案:

/sf/answers/1704743281/

我问这个的原因有点奇怪。我目前正在将一些 Cucumber 测试重构为 Rspec 功能规范。其中一些是作为“设置”步骤向我们的应用程序中的端点发出getpost发出命令。例如,有一个端点用于启用数据库记录中的某个标志。我可以只设置带有标志集的数据库对象,但我想尽可能忠实于原始的 Cucumber 代码(至少一开始是这样)。

所以现在我可以这样做(并且它有效):

require "features_helper"

RSpec.feature "Simple Feature", type: :feature do
  scenario "a test scenario" do
    session = ActionDispatch::Integration::Session.new(Rails.application)
    response = session.get("/")
    # or I could do: session.post("/api/xyz", params: { one: "one", two: "two" })
  end
end
Run Code Online (Sandbox Code Playgroud)