[英]Undefined method `save' for nil:NilClass in RSpec test
I have a Page
resource for which the create
action in the pages_controller.rb file looks as follows: 我有一个Page
资源, pages_controller.rb文件中的create
操作如下所示:
def create
@page = Page.new(page_params)
if @page.save
flash[:notice] = "#{@page.name} was created successfully."
redirect_to pages_url
else
render 'new'
end
end
private
def page_params
params.require(:page).permit(:name, :content)
end
And the following test in the pages_controller_spec.rb file: 以及pages_controller_spec.rb文件中的以下测试:
describe PagesController do
describe "POST Create'" do
it "creates a new page" do
Page.should_receive(:new)
post :create, page: {name: "Foo", content: "Bar"}
end
end
end
Which produces the following error: undefined method 'save' for nil:NilClass 这会产生以下错误: nil的未定义方法'save':NilClass
I'm just starting out with RSpec; 我刚刚开始使用RSpec; so surely I've either made a mistake or I am overlooking something simple. 所以我肯定犯了一个错误,或者我忽略了一些简单的事情。 Also, I'm following the "RSpec Book", which goes on to add: page = mock_model(Page).as_null_object
right before Page.should...
, but I'm still getting the same error. 另外,我正在关注“RSpec Book”,它继续在Page.should...
之前添加: page = mock_model(Page).as_null_object
,但我仍然得到同样的错误。 Any ideas? 有任何想法吗? Thanks in advanced. 提前致谢。
With 同
Page.should_receive(:new)
you're essentially stubbing it. 你基本上是抄袭它。 This is short for: 这是简短的:
Page.should_receive(:new).and_return(nil)
That's why you're getting the error on nil:NilClass. 这就是你在nil上得到错误的原因:NilClass。 What you could do is either chaining a call to and_call_original , which would look like this: 你可以做的是链接一个对and_call_original的调用,它看起来像这样:
Page.should_receive(:new).and_call_original
or you specifically return a mock, something along the lines of: 或者你特意返回一个模拟,类似于:
Page.should_receive(:new).and_return(mock_model(Page))
你有夹具文件夹中的page.yml可能是因为它没有保存页面。在我的应用程序中我添加了蓝色print.rb我的模型的结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.