我正在尝试学习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相关的配置问题有关。但为什么它不起作用以及如何改变呢?
干杯
答案 0 :(得分:0)
当你执行这样的should_receive时,它将返回nil,因此下一行(设置flash消息时)尝试从nil检索标题。将您的should_receive更改为:
Movie.should_receive(:create!).with({"title" => 'Milk', "rating" => 'R'}).and_return(stub_model(Movie))