Rspec 错误 - 当前用户与另一个模型之间的关系

发布于 2024-11-03 01:37:16 字数 716 浏览 1 评论 0原文

我正在测试我的员工控制器,在登录用户的索引测试中,我收到一个似乎与我的模型关系相关的错误。

测试是:

describe "for signed-in user" do
  before(:each) do
    @user = test_sign_in(Factory(:user))
  end

  it "should have the right title" do
    get :index
    response.should have_selector('title', :content => "Employee List")
  end

我设置了 render_views 。我还将每个用户绑定到一个位置,并且员工索引视图应该显示用户位置的员工。在我的索引视图中,我有以下代码来显示员工位置的名称:

<h1>Listing employees for <%= current_user.location.name %> </h1>

当我运行测试时,我收到一条错误消息,其中包含 “ActionView::模板::错误: undefined method 'name for nil:NilClass"

在我的factories.rb文件中,我确实将用户的位置id设置为有效id。为什么current_user.location返回nil?我在测试中缺少什么?谢谢!

I am testing my employees_controller, and in my index test for signed-in users, I am getting an error that seems to be related to my model relationships.

The test is:

describe "for signed-in user" do
  before(:each) do
    @user = test_sign_in(Factory(:user))
  end

  it "should have the right title" do
    get :index
    response.should have_selector('title', :content => "Employee List")
  end

I have render_views set. I also have each user tied to a location, and the employee index view is supposed to show employees for the user's location. And in my index view, I have the following code to show the name of the location of the employees:

<h1>Listing employees for <%= current_user.location.name %> </h1>

When I run my test, I get an error message that contains
"ActionView::Template::Error:
undefined method 'name for nil:NilClass"

In my factories.rb file, I did set the user's location id to a valid id. Why is current_user.location returning nil? What am I missing in the test? Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

人疚 2024-11-10 01:37:16

最有可能的是,这只是登录过程不正确。我就是这样做的。我有一个 /spec/support/controller_macros.rb 和里面:

module ControllerMacros
  def login_user
    before(:each) do
      @request.env["devise.mapping"] = :user
      @user = Factory(:user)
      sign_in @user
    end
  end
end

现在,在我的控制器规格中:

describe AbilitiesController do
    login_user

  describe "POST 'train' ..." do
    ...
  end
...

Most probably, it's just that the login process in not correct. This is how i do it. I have a /spec/support/controller_macros.rb and inside :

module ControllerMacros
  def login_user
    before(:each) do
      @request.env["devise.mapping"] = :user
      @user = Factory(:user)
      sign_in @user
    end
  end
end

Now, in my controller specs :

describe AbilitiesController do
    login_user

  describe "POST 'train' ..." do
    ...
  end
...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文