【问题标题】:problem with rspec test, undefined method 'post'rspec 测试的问题,未定义的方法“post”
【发布时间】:2011-08-20 23:32:38
【问题描述】:

我正在编写一个规范来测试当有人通过 URL 发送查询时 mashup_controller 的行为。我需要模拟 URL 中包含的参数,并且我读到 post() 方法会这样做,但是当我收到错误时:

1) MashupController simulates query
     Failure/Error: post :create
     NoMethodError:
       undefined method `post' for
#<RSpec::Core::ExampleGroup::Nested_1:0x980bc50>
     # ./mashup_controller_rspec.rb:9:in `block (2 levels) in <top (required)>'

Finished in 0.20199 seconds 1 example, 1 failure

Failed examples:

rspec ./mashup_controller_rspec.rb:7 # MashupController simulates query

这是我的代码:

require 'spec_helper'
require 'mashup_controller.rb'

describe MashupController do
    it "simulates query" do
        post :create    
    end
end

对不起,如果我没有任何意义。我对 Rails 和 rspec 很陌生。任何帮助,将不胜感激。谢谢。

【问题讨论】:

  • 显示您的目录结构。另外,您使用的是什么版本的rails?这个混搭控制器是否继承自 ApplicationController?
  • 是的,MashupController 确实继承自 ApplicationController。 mashup_controller.rb 在另一个目录中,但我将它添加到 $LOAD_PATH,所以我认为这不是问题所在。另外,我正在运行 Ruby 1.9.2、Rails 3.0.1 和 rspec-rails 2.6.1。我想知道我是否只是设置了错误。

标签: ruby-on-rails ruby rspec tdd bdd


【解决方案1】:

如果规范文件不在spec/controllers 下,rspec-rails 将不会自动提供getpost 等方法。

您需要标记您的规范:

describe MyController, type: :controller do
  # ...
end

或包含模块:

describe MyController do
  include RSpec::Rails::ControllerExampleGroup
  # ...
end

the relevant code in rspec-rails

【讨论】:

    【解决方案2】:
    1. 确保您的 Gemfile 中有 gem spec-rails
    2. 您的mashup_controller_rspec.rb 应该在spec/controllers 之下

    【讨论】:

    • 您的测试也可以在规范/请求下,他们将能够发布等。
    【解决方案3】:

    我使用 gem rspec-rails 而不是 gem spec-rails。

    【讨论】:

      【解决方案4】:

      在 Rails 4 中,您可以将 RSpec 测试的类型声明为 :request,并且 spec 文件可以在任何目录中。

      example: in spec/routes/users.rb
      RSpec.describe 'UserRoutes', type: :request do
        ...
      end
      

      【讨论】:

        【解决方案5】:

        我的解决方案是

        describe MyController, type: :controller
        ...
        end
        

        【讨论】:

          猜你喜欢
          • 2014-10-23
          • 1970-01-01
          • 1970-01-01
          • 2018-04-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-18
          相关资源
          最近更新 更多