简体   繁体   中英

Rails view specs: can't locate partials in namespaced views

I trying to get my head wrapped around testing with RSpec. One of the problems I'm running into is getting RSpec to locate partials when calling render in a test for a view in the admin namespace.

Essentially, in my vieww, I have lots of render calls that use the abbreviated syntax, like this:

render @products

But, I guess because RSpec lacks the context of knowing that this view is in the admin namespace, it can't seem to find the partial located in app/views/admin/products/_product.html.erb . To get things working, I have to do something like:

render partial: 'admin/products/product', collection: @products

But, you know, I'm quite attached to the shorter syntax. It's kinda the whole point of following the Rails conventions. The reward for being such a good boy and putting everything in it's proper place, if you will.

So, I was wondering: is there is a way in my RSpec view test to specify that I am testing a view within a certain namespace? Is there some golden nugget that will make this pain go away?

If you feel this really is an RSpec isssue, please log it on the rspec-rails issues . Based on your general description, this sounds like a rails issue.

When you use render @products in a view, that tells Rails to render a partial . This is different from a render inside the controller action.

According to the Rails docs , when you render @customer :

@customer instance variable contains an instance of the Customer model, this will use _customer.html.erb to render it.

What this is leaving out is the path for _customer.html.erb . Unfortunately, the current docs make you hunt for this. Under the collection info, is this gem:

Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection:

What this essentially means is that, in your view, when you perform render @customer , this attempt to load: app/views/customers/_customer.html.erb . Not the namespace you have setup already. If you wish to use the namespace, your model must either already be part of that namespace (ie Admin::Product ) or you must specify the full partial path (as you have already found out).

I know this is an old question but this link https://github.com/rspec/rspec-rails/issues/396 might help anyone else (like me) who has faced a similar issue. You can configure where an rspec spec will look for view partials on a spec by spec basis.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM