【发布时间】:2013-02-10 13:32:15
【问题描述】:
使用 Rails 3.2.11
我有几个视图 rspec 测试,我需要在其中存根“current_user”调用。
我已经在常规视图测试中成功使用了它,如下所示:
require 'spec_helper'
describe "projects/_my_project.html.erb" do
before(:each) do
@client = FactoryGirl.create(:user)
view.stub(:current_user) { @client }
end
describe "new proposals notice" do
it "does not display new_propsals if in state posted and clicked after last submitted" do
@my_project = FactoryGirl.build(:project, status: "posted", last_proposals_click: "2012-02-02 14:01:00", last_proposal_submitted: "2012-02-02 14:00:00")
render :partial => "/projects/my_project", :locals => { :my_project => @my_project }
rendered.should_not have_content "You received new proposals"
end
end
end
Current_user 由 Devise 在 controllers/helpers.rb(在 gem 中)中定义。我在视图或控制器中到处使用它作为 current_user(作为方法,而不是实例)。
问题似乎在于 view.stub 中的 view 在这里为零,是否还有另一个对象在局部使用的情况下使用?我只是不明白为什么这在常规视图中是完美的,而不是在局部视图中。
我明白了:
Failure/Error: view.stub(:current_user) { @client }
NoMethodError:
undefined method `view_context' for nil:NilClass
这是视图中的行,其中 current_user 用于完整性:
<% if my_project.user_id == current_user.id %>
有谁知道我如何让它成功存根 current_user,我在这里不知所措......
谢谢
【问题讨论】:
-
@user是测试替身/模拟模型吗? -
嗨,这是 FactoryGirl 创建的模型。
-
您能否发布任何其他相关代码,例如您的
User工厂,或者您如何访问current_user(通过对current_user的方法调用或使用实例变量@current_user。 ..),也许还有你试图存根的视图代码的 sn-p。另外,here 或 here 或 this blog post 的任何 SO 答案都不能帮助您吗? -
嗨,添加了完整的测试代码和更多信息;不幸的是,引用的解决方案对我不起作用。
-
如果您更改视图代码以删除对
id的调用,是否会发生任何变化?即<% if my_project.user_id == current_user %>
标签: ruby-on-rails rspec