【问题标题】:Rspec what is wrong with my test for create controller action?Rspec 我对创建控制器操作的测试有什么问题?
【发布时间】:2012-03-31 02:34:06
【问题描述】:

我正在尝试学习 TDD,这是我的家庭作业的一部分,我不知道该怎么做。

我想测试create 控制器动作,这是我的测试代码:

require 'spec_helper'

describe MoviesController do
  describe 'create' do
    it 'should call the model method perform create!' do
      Movie.should_receive(:create!).with({"title" => 'Milk', "rating" => 'R'})
      post :create, :movie => {:title => 'Milk', :rating => 'R'}
    end
  end
end

但我得到了:

Failures:

  1) MoviesController create should call the model method performe create!
     Failure/Error: post :create, :movie => {:title => 'Milk', :rating => 'R'}
     NoMethodError:
       undefined method `title' for nil:NilClass
     # ./app/controllers/movies_controller.rb:50:in `create'
     # ./spec/controllers/movies_controller_spec.rb:7:in `block (3 levels) in <top (required)>'

Finished in 0.21714 seconds

这是我正在测试的创建操作。是的,它是 TDD,是的,我正在测试一个 工作代码,这是测试不起作用:D

 def create
    @movie = Movie.create!(params[:movie])
    flash[:notice] = "#{@movie.title} was successfully created."
    redirect_to movies_path
 end

我什至不知道为什么我会收到未定义的方法错误消息?我通过了其他一些测试,但为简单起见,我在此代码片段中删除了,所以我认为这与 db/model 相关的配置问题无关。但是为什么它不起作用以及如何更改它?

干杯

【问题讨论】:

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


    【解决方案1】:

    当你像这样执行 should_receive 时,它​​将返回 nil,因此下一行(设置 flash 消息时)会尝试从 nil 中检索标题。将您的 should_receive 更改为:

      Movie.should_receive(:create!).with({"title" => 'Milk', "rating" => 'R'}).and_return(stub_model(Movie))
    

    【讨论】:

    • Should_receive 将返回 nil,即使它确实收到了匹配参数 "{"title" => 'Milk', "rating" => 'R'}" 所以我需要捕获返回值,我做对了吗?
    • 对不起,我现在知道了,它来自控制器线。谢谢@ctide,拯救了我的一天!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多