簡體   English   中英

如何使用RSpec在Rails 4中測試質量分配

[英]How to test Mass Assignment in Rails 4 using RSpec

給定一個簡單的用戶模型,在Rails 4中使用名稱,電子郵件和一個管理員布爾值,使用RSpec測試批量分配的最佳方法是什么?

這是UsersController:

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

private

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

以及兩種不同的測試方法:

在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方法不是私有的。 (官方文檔建議將其設置為private。注意-監視user_spec中的MassAssignment錯誤也不起作用(不會引發錯誤)。

注意-實際上,將用戶正確設置為視圖中的用戶是可行的-admin屬性被過濾掉了,一切都很好,但確實希望在測試中能正常工作。

另一種建議是將shoulda-matchers gem與user_spec.rb一起使用:

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)造成的。

提前致謝!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM