[英]Rspec Test controller render partial with locals
I have controller action like 我有控制器动作,例如
def get_status
status_name = current_user.status
status_updated_time = current_user.updated_at
render :partial => 'show_status', :locals => {status_name: status_name, status_updated_time: status_updated_time}
end
here I am planning to test local variable values which are passing via render partial. 在这里,我计划测试通过渲染局部传递的局部变量值。 ie 即
status_name
, status_updated_time
. status_name
, status_updated_time
。
Could you please let me know how to write rspecs for render partial with locals in controller. 您能否让我知道如何编写rspecs以便在控制器中使用局部变量进行渲染。
I would move variable logic into a separate method: 我将变量逻辑移到单独的方法中:
def get_status
render partial: 'show_status', locals: get_status_from(current_user)
end
protected
def get_status_from(user)
{ status_name: user.status, status_updated_time: user.updated_at }
end
and test that method instead. 并测试该方法。
I would say that to test the controller, what you're after is a basic feature/integration spec wherein you can simply look for the content held by your partial. 我想说,要测试控制器,您所追求的是一个基本的功能/集成规范,您可以在其中简单地查找您的部件所拥有的内容。
feature 'SomeController' do
background do
# setup data
# and anything else you need for authentication, etc. as your site dictates
end
scenario 'viewing the get status page' do
visit some_controller_get_status_path
expect(page).to have_text('WHATEVER IS IN THE LOCAL VAR')
end
end
I prefer to use feature specs over controller specs as I seek (but often fail!) to keep my controllers so simple that there is not really much to test in them. 我倾向于(而不是经常失败!)使用功能规格而不是控制器规格来使我的控制器保持如此简单,以至于它们中没有太多要测试的东西。 With feature specs, I feel like I'm getting more from the test in terms of how my app works, etc. 有了功能规格,我觉得我的应用程序的工作方式等方面的测试使我受益匪浅。
EDIT: sorry ... hit enter too early :). 编辑:对不起...打回车太早了:)。
For a controller, you could directly test the var value along the lines of: 对于控制器,您可以按照以下方式直接测试var值:
describe "Your Controller", :type => :controller do
describe "GET get_stuff" do
it "assigns a value to status_name" do
get :get_status
expect(assigns(:status_name)).to eq(['VALUE'])
end
end
end
That may not be 100% spot-on for a controller spec (again, I don't use them a lot) but I think it should get you on your way should you go controller spec over feature/integration spec. 对于控制器规范来说,这可能不是100%正确(再次,我不常使用它们),但我认为,如果您将控制器规范推向功能/集成规范,那应该会助您一臂之力。
you could do something like 你可以做类似的事情
it "should render correct partial for get_status" do
controller.should_receive(:render).with({
:partial => '_show_status', #here you will have to give the full path like <controller_name>/_show_status
:locals => {status_name: <name>, status_update_time: <time>}
})
get 'get_status'
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.