[英]Specify URL parameters in Rails integration test / RSpec request spec
[英]Rspec view test with url parameters
我有一个页面dashboard.html.erb
,可以从几个不同的控制器/动作重定向到该页面。 接收到重定向后,它还会接收几个url参数。
控制器代码:
class PlansController
def some_action
redirect_to dashboard_path(show: "default", cool_array: ["test", "test"])
end
end
class StaticpagesController
def dashboard
end
end
查看代码:
<% if cool_array %>
<% cool_array.each do |a| %>
<li><%= a %></li>
<% end %>
<% end %>
<script>
var show = getParamFromURL("show")
// some sort of function that returns the value of the show param, in this case, "default"
if (show == "default") {
$("#default").addClass("show");
} else {
$("#other").addClass("hidden");
}
</script>
由于这些是重定向,因此无法使用render_views
控制器测试。 因此,我考虑过要构建测试,以便控制器规范测试是否传递了正确的参数,而视图规范测试了是否存在某些参数,存在正确的css类,等等。 但是在我看来,我在模拟参数传递方面遇到了麻烦。
这似乎是我发现的唯一其他问题: RSpec View测试:如何修改参数?
但是,没有一种解决方案对我有用。 我不确定在这种情况下我是否需要一个助手...这似乎有点作弊...
我已经尝试了(从上面的链接的SO问题):
before do
controller.request.path_parameters[:cool_array] = ["test","test"]
end
# => ActionView::Template::Error:
# undefined local variable or method `cool_array' for #<#<Class:0x007fe2d9815100>:0x007fe2d90a62e8>
# thrown by line in view file with <% if cool_array %>
before do
view.stub(:params).and_return({cool_array: ["test", "test"]})
end
# => ActionView::Template::Error:
# undefined local variable or method `cool_array' for #<#<Class:0x007fe2d9815100>:0x007fe2d90a62e8>
# thrown by line in view file with <% if cool_array %>
helper.params = {:cool_array => ["test", "test"]]}
# honestly not even sure this is right, because it can only go into a describe block (not a before, not an it) and then it throws:
# NoMethodError:
# undefined method `params=' for #<#<Class:0x007fd7cc8f4930>:0x007fd7cc8a5060>
他们都失败了:
由于这些是重定向,因此无法使用render_views进行控制器测试。
不,您只是在做错事。
如果StaticpagesController#dashboard
接受url参数,则应在StaticpagesController控制器规范中测试它如何响应上述参数。
RSpec.describe StaticpagesController, type: :controller do
describe 'GET #dashboard' do
render_views
it "does something with the x parameter" do
get :dashboard, x: 'hello!'
expect(response.body).to match 'hello!'
end
end
end
同样,您应该测试PlansController#some_action是否在响应中包含正确的参数。
我认为您的视图规范问题告诉您,您的视图中有代码味道。 在MVC中,您的控制器负责获取输入并将其传递给视图和模型。 将视图与直接处理参数隔离开,意味着处理该参数的参数不会在整个应用程序中重复。
用locals
在你的控制器传递变量你的意见,并避免使用params
在你的意见。
它可以实现更好的设计和更轻松的测试:
describe "rendering locals in a partial" do
it "displays the widget" do
widget = stub_model(Widget, :name => "slicer")
render :partial => "widgets/widget.html.erb", :locals => {:widget => widget}
rendered.should contain("slicer")
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.