rails minitest not picking up fixture properly, instance variable not percolating

24 Views Asked by At

The following test has the purpose of ensure that any visitor is assigned a role

  test "role for non logged in user" do
    get root_path
    puts ('role ' + @role.to_s)
    assert @role == 'end consumer'
  end

the role can change based on a join table where a shop is known via the host and the process is invoked in the application controller with before_action :set_clean_host_site this method in turn calls a method in a concern to set the role

  def set_clean_host_site
    rurl = request.host  
    if request.subdomains.empty?
      rurl = 'www.' + rurl
    end
    clean_host = rurl.chomp("/")
    @site = Site.where('host = ?', clean_host.to_s).first
    if @site
      session[:active_shop_id] = @site.shop_id
      @shop = Shop.find(@site.shop_id)
      set_role
    else
      @shop = Shop.find(1)
    puts @shop.inspect
      session[:active_shop_id] =  @shop.id      
      set_role
    puts @role
    end
  end

  def set_role
    if current_user
      cu_rsu = Roleshopuser.where('user_id = ? AND shop_id = ?', current_user.id, @shop.id ).first 
      if cu_rsu
        @role = cu_rsu.role.name
      end
    else
      @role = 'consumer'
    end
  puts @role
  end

a shops.yml fixture contains:

id_one:
  id: 1
  name: MyString
  nation: one
  slug: MyString

Thus two observations are derived.

  1. the fixture with its id (1) for a shop is not found. but that should not impede the method to complete..
  2. the set_role should be fired; the method is a fallback to ensure a role is attributed. The "puts" yield [blank for shop]:

consumer
consumer
role 

and thus the test visibly does not have access to the instance variable.

What is going on / wrong with this approach?

1

There are 1 best solutions below

2
sam On

This isn't really how to use fixtures. If you want to get a specific fixture, for example, this one:

id_one:
  name: MyString
  nation: one
  slug: MyString

Don't assign an id. Then in your test class call shops(:id_one). Minitest will grab the correct shop fixture from that.

Since those names (ie id_one) are up to you, people tend to give them names with meaning, for instance roles. Note how you can assign a fixture to another fixture using the name of the fixture (as opposed to the id).

# fixtures/users.yml
owner:
  name: An Owner

consumer:
  name: A Shopper

# fixtures/shops.yml
department_store:
  name: ABC Department Store 

# fixtures/roles.yml
owner:
  name: owner

consumer:
  name: consumer

# fixtures/roleshopuser.yml
owner:
  user: owner
  shop: department_store
  role: owner

consumer:
  user: consumer
  shop: department_store
  role: consumer