【问题标题】:view.stub in rails partial rspec gives 'undefined method view_context'rails partial rspec 中的 view.stub 给出“未定义的方法 view_context”
【发布时间】: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。另外,hereherethis blog post 的任何 SO 答案都不能帮助您吗?
  • 嗨,添加了完整的测试代码和更多信息;不幸的是,引用的解决方案对我不起作用。
  • 如果您更改视图代码以删除对id 的调用,是否会发生任何变化?即&lt;% if my_project.user_id == current_user %&gt;

标签: ruby-on-rails rspec


【解决方案1】:

事实证明,将 view.stub(:current_user) { @client } 移动到每个“it”块中解决了问题;如果它在 'before:each/all' 块中,它似乎不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多