Rails rspec with FactoryGirl and instance variables
<p>I do not write tests very well and I have some trouble using instance variable from Application Controller for another controllers in test.
In Rails I had a pretty simple controller action.</p>

<pre><code>  def index
    @cities = City.all
    @starred_cities = @cities.where(starred: true)
  end
</code></pre>

<p>For this action I have a test:</p>

<pre><code>RSpec.describe CitiesController, :type =&gt; :controller do
  let(:city) { create(:city) }

  describe 'GET #index' do
    let(:cities) { create_list(:city, 2) }
    before { get :index }

    it 'populates an array of all cities' do
      expect(assigns(:cities)).to match_array(cities)
    end

    it 'renders index view' do
      expect(response).to render_template :index
    end
  end
end
</code></pre>

<p>In application I need to get a country by domain name and set globally for all controllers. I add to ApplicationController before_action method like this:</p>

<pre><code>before_action :get_country
def get_country
  country_slugs = {en: 'usa', ru: 'russia', es: 'spain'}
  current_country_slug = country_slugs[I18n.locale]
  @country = Country.find_by_slug(current_country_slug)
end
</code></pre>

<p>And now I can get cities in my controller only for current country:</p>

<pre><code>def index
  @cities = @country.cities
  @starred_cities = @cities.where(starred: true)
end
</code></pre>

<p>Now I have some trouble because my controller test fails with exception:</p>

<pre><code>Failures:

1) CitiesController GET #index populates an array of all cities
  Failure/Error: @cities = @country.cities

  NoMethodError:
   undefined method `cities' for nil:NilClass
   # ./app/controllers/cities_controller.rb:5:in `index'
   # ./spec/controllers/cities_controller_spec.rb:9:in `block (3 levels) in &lt;top (required)&gt;'

2) CitiesController GET #index renders index view
  Failure/Error: @cities = @country.cities

  NoMethodError:
   undefined method `cities' for nil:NilClass
  # ./app/controllers/cities_controller.rb:5:in `index'
  # ./spec/controllers/cities_controller_spec.rb:9:in `block (3 levels) in &lt;top (required)&gt;'
</code></pre>

<p>Please help, what should I do to combine such instance variable and make an association on it?</p>