1

名前、電子メール、および管理者ブール値を持つRails 4の単純なユーザーモデルが与えられた場合、RSpecを使用して大量割り当てをテストするための最良のアプローチは何ですか?

ユーザーコントローラーは次のとおりです。

def create
  @user = User.new user_params
  ...snip
end

private

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

これをテストするための2つの異なる試行:

user_spec.rb で

describe "accessible attributes" do
  describe "should not allow access to admin" do
    before do 
      @user.admin = "1"
      @user.save
    end
    it { should_not be_admin }
  end
end

または users_controller_spec.rb で

it 'should only allow name and email to be set' do
  @controller.user_params.keys.should eq(['name', 'email')
end

どちらも機能しません - 前者は admin を true に設定してユーザーを作成するだけです (テストに失敗します) - おそらくこれは strong_parameters をバイパスします。後者は機能しますが、user_params メソッドがプライベートでない場合のみです。(公式ドキュメントでは、プライベートに設定することを推奨しています。注 - user_spec で MassAssignment エラーを監視しても機能しません (エラーは発生しません)。

注 - 実際には、ビューでユーザーを管理者に設定すると正しく機能します。管理者属性は除外され、すべて問題ありませんが、テストでこれが適切に機能することを本当に望んでいます。

別の提案は、user_spec.rb で shoulda-matchers gem を使用することです。

describe User do
  ...
  it { should_not allow_mass_assignment_of(:admin) }
  ...
end

(これも機能しません)、次を与えます:

Failure/Error: it { should_not allow_mass_assignment_of(:admin) }
 NoMethodError:
   undefined method `active_authorizer' for #<Class:0x007f93c9840648>

(このエラーは、shoulda-matchers がまだ Rails 4 に対応していないことが原因であると思います)。

前もって感謝します!

4

1 に答える 1

0
it "should not allow mass assignment" do
  raw_parameters = { :admin => 1 }
  parameters = ActionController::Parameters.new(raw_parameters)
  expect {@user.update_attributes(parameters)}.should raise_error
end

質量の割り当てをテストするには、コントローラーから渡されるパラメーターをシミュレートする必要があります。

https://github.com/rails/strong_parameters#use-outside-of-controllers

于 2013-02-28T14:37:02.727 に答える