ruby-on-rails - 如何测试 Controller 规范中的 strong_parameters?

标签 ruby-on-rails ruby rspec ruby-on-rails-4 strong-parameters

我想在添加 strong_parameters gem 后测试我的 Controller ,该怎么做? 我试过:

Controller

class EventsController < ApplicationController
  def update
    @event = Event.find(params[:id])
    respond_to do |format|
      if @event.update_attributes(event_params)
        format.html { redirect_to(@event, :notice => 'Saved!') }
      else
        format.html { render :action => "new" }
      end
    end
  end

  private
  def event_params
    params.require(:event).permit!
  end
end

规范

describe EventsController do
  describe "PUT update" do
    describe "with forbidden params" do
      let(:event) { Event.create! title: "old_title", location: "old_location", starts_at: Date.today }

      it "does not update the forbidden params" do
        put :update,
          id: event.to_param,
          event: { 'title' => 'new_title', 'location' => 'NY' }

        assigns(:event).title.should eq('new_title') # explicitly permitted
        assigns(:event).location.should eq("old_location")  # implicitly forbidden

        response.should redirect_to event
      end
    end
  end
end

错误

1) EventsController PUT update with forbidden params does not update the forbidden params
   Failure/Error: assigns(:event).title.should eq('new_title') # explicitly permitted
   NoMethodError:
     undefined method `title' for nil:NilClass
   # ./spec/controllers/events_controller_spec.rb:13:in

最佳答案

我看到这里发生了一些事情。

第 13 行显示 undefined method 是因为 @event 变量没有被赋值,所以 assigns(:event) 返回 nil。 您应该检查为什么会这样,也许您有一些身份验证阻止您更新记录?也许您可以查看测试日志以了解实际情况。
这可能是因为您正在使用 let() ,它是惰性的,并且当您尝试搜索它时记录实际上还不可用,但我不完全确定。您可以尝试使用 let!() 看看是否有帮助。

关于强参数的实际使用,如果你只想让title可赋值,你需要做类似下面的事情:

params.require(:event).permit(:title)

如果您使用permit!,事件参数哈希和每个子哈希都被列入白名单。

关于ruby-on-rails - 如何测试 Controller 规范中的 strong_parameters?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15520928/

相关文章:

ruby-on-rails - Rails RSpec 测试简单链接redirect_to 路径

ruby-on-rails - Ruby on Rails 截断阅读更多

ruby-on-rails - 试图通过电子邮件查找用户并获取 "Called id for nil"

ruby - FactoryGirl 覆盖关联对象的属性

ruby-on-rails - : rspec stub(:new). 这里发生了什么......?

ruby-on-rails - Rails 时区和夏令时

ruby - 从 Ruby 运行交互式程序

ruby - 如何使用 prawn 更改现有 pdf 的方向?

ruby-on-rails - 如何测试变量未定义或RSpec中引发异常

ruby-on-rails - 分解您的 RSpec 测试