Ruby on rails 如何用Rspec测试强参数?

Ruby on rails 如何用Rspec测试强参数?,ruby-on-rails,ruby,ruby-on-rails-4,rspec,rspec-rails,Ruby On Rails,Ruby,Ruby On Rails 4,Rspec,Rspec Rails,用Rspec测试Rails控制器中的强参数过滤的实际策略是什么?(除了shoulda matchers)如何编写失败的测试,然后将其变为绿色?使用预期和所有(未满足要求的)参数创建2个哈希。然后将所有参数传递给操作,并检查对象模型是否只接收预期的参数。如果不使用强参数过滤器,则不会出现这种情况。然后将权限添加到参数并再次检查测试 例如,这: # action def create User.create(params) end # spec it 'creates a user' do

用Rspec测试Rails控制器中的强参数过滤的实际策略是什么?(除了shoulda matchers)如何编写失败的测试,然后将其变为绿色?

使用预期和所有(未满足要求的)参数创建2个哈希。然后将所有参数传递给操作,并检查对象模型是否只接收预期的参数。如果不使用强参数过滤器,则不会出现这种情况。然后将权限添加到参数并再次检查测试

例如,这:

# 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)
更改操作,测试将通过。

以下是我的操作方法:

  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
我个人用的是thoughtbot

比如:

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

就像您使用强参数创建或更新对象一样,它也类似,只是有一件事您可以这样做:

帖子:创建,book_id:@book.id

但在强参数中,您必须这样做:

帖子:创建,{book_id:@book.id,注释:{user_id:101,book_id: @book.id,描述:“值得购买”}}


您必须传入嵌套参数。

我的回答有帮助吗?也许我可以澄清一些事情。谢谢你,你真的帮助了我。我不知道你有什么机会。以及如何测试属性需求,如params.require:user?
create
是在
ActiveRecord::Base
上定义并由
user
继承的类级方法。因此,虽然
expect\u任何实例(用户)
(对
User
实例的模拟期望)可能会起作用,但
expect(用户)
(对
User
类的模拟期望)也会起作用,而且会更为简单。