-->

Fixtures with polymorphic association not working

2019-08-27 12:56发布

问题:

I'm trying to implement the Rolify gem but have trouble adding fixtures with a scope for it. The last line of the (model) test below fails because currently the moderator role seems to be given to @user globally instead of only for organization one. The fixtures below aren't using resource_id and resource_type, which are mentioned in the gem documentation for fixtures, but I'm not sure how to use them. How should I set the scope for the moderator role to only organization one?


roles.yml

moderator:
  id: 1
  resource: one (Organization)

users.yml

one:
  email: example@example.com
  roles: moderator, organizations(:one)           # I was hoping this would set the scope of the role to organization one but it isn't (seems to set the role globally).

test.rb

def setup
  @moderator_role = roles(:moderator)
  @organization1  = organizations(:one)
  @organization2  = organizations(:two)
  @user           = users(:one)
end

test "should be moderator if fixtures correct" do 
  assert_equal @user.has_role?('moderator'), true
  assert_equal @user.has_role?(:moderator, @organization1), true
  assert_equal @user.has_role?(:moderator, @organization2), false       # This line fails
end

Update: I also tried the code below. But still the test fails.

roles.yml

moderator:
  name: :moderator
  resource: one (Organization)

users.yml

one:
  organization: one
  roles: moderator, organizations(:one)

organizations.yml

one:
  name: "Company A"

test.rb

def setup
  @moderator_role = roles(:moderator)
  @organization1  = organizations(:one)
  @organization2  = organizations(:two)
  @user           = users(:one)
end

test "should be moderator if fixtures correct" do 
  assert_equal @user.has_role?('moderator'), true                      # This line fails
  assert_equal @user.has_role?(:moderator, @organization1), true       # This line also fails
  assert_equal @user.has_role?(:moderator, @organization2), false
end

回答1:

I found out that with the code in the update, the test does pass if I run it as a users controller test or integration test, instead of as a model test. So I guess I was just running it as the wrong type of test.