如何用Rspec测试强对数?

使用Rspec在Rails控制器中测试强params过滤的实际策略是什么? (除了应该匹配)如何编写失败的测试然后使其变为绿色?

创建具有预期和所有(具有不满足)参数的2个哈希。 然后将所有参数传递给动作并检查您是否对象模型仅接收预期的参数。 如果您没有使用强参数filter,则不会。 然后添加权限params并再次检查测试。

例如,这个:

# action def create User.create(params) end # spec it 'creates a user' do expect_any_instance_of(User).to receive(:create). with({name: 'Sideshow Bob'}.with_indifferent_access) post :create, user: { first_name: 'Sideshow', last_name: 'Bob', name: 'Sideshow Bob' } end 

将所有参数传递给用户,测试将失败。 当你过滤它们时:

 def user_params params.require(:user).permit(:name) end 

并使用User.create(user_params)更改操作,test将通过。

我个人使用来自thinkbot的shoulda-matcher 。

有类似的东西:

 it do should permit(:first_name, :last_name, :email, :password). for(:update, params: params) end 

我是这样做的:

  describe 'Safe Params' do let(:mixed_params) { { blueprint_application_environment: { id: 1000, blueprint_id: 1, application_id: 2, environment_id: 3 }, format: :json } } context "when processing a Post request with a mix of permitted and unpermitted parameters" do before { post :create, mixed_params } it "a create will not set the value of the unpermitted parameter" do expect(JSON.parse(response.body)["id"]).not_to eq(1000) end it "a create will set the value of the permitted parameters" do expect(JSON.parse(response.body)["blueprint_id"]).to eq(1) expect(JSON.parse(response.body)["application_id"]).to eq(2) expect(JSON.parse(response.body)["environment_id"]).to eq(3) end end 

结束

控制器代码:

  def create @blueprint_application_environment = BlueprintApplicationEnvironment.new(blueprint_application_environment_params) if @blueprint_application_environment.save render 'show.json.jbuilder' else render json: @blueprint_application_environment.errors, status: :unprocessable_entity end end def blueprint_application_environment_params params.require(:blueprint_application_environment).permit(:blueprint_id, :application_id, :environment_id) end 

就像你使用强参数创建或更新对象一样,它也是类似的,除了正常你喜欢这样的一件事:

post:create,book_id:@ book.id

但是在强参数中你必须这样做:

发布:创建,{book_id:@ book.id, 评论:{user_id:101,book_id:@ book.id,描述:“值得购买”} }

你必须传入嵌套参数。