私はテストをあまりうまく書いていないので、テスト中の他のコントローラ用のApplication Controllerからのインスタンス変数を使っていくつか問題があります。 Railsではかなり単純なコントローラアクションがありました。このアクションのRails rspecでFactoryGirlとインスタンス変数
def index
@cities = City.all
@starred_cities = @cities.where(starred: true)
end
私がテストしています。アプリケーションで
RSpec.describe CitiesController, :type => :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
を私はドメイン名で国を取得し、すべてのコントローラにグローバルに設定する必要があります。私はこのようなApplicationControllerにするbefore_actionメソッドに追加します。
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
そして今、私は、現在、国のために私のコントローラ内の都市を取得することができます:私のコントローラのテストが例外で失敗するので
def index
@cities = @country.cities
@starred_cities = @cities.where(starred: true)
end
は今、私はいくつかの問題があります:
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 <top (required)>'
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 <top (required)>'
このようなインスタンス変数を組み合わせて関連付けるにはどうすればよいですか?
国の作成はどこですか?国がnilにデフォルト設定されているため例外が発生しています。 –
'@ country'をどこで初期化していますか? – max
@countryは 'before_action:get_country'から来ます。 – sixty4bit