How do I stub out a current user's attributes in a view spec

Deadly 提交于 2019-12-04 20:42:31

You have stubbed the method named current_user, not the instance variable @current_user.

view.stub(:current_user).and_return(@user)

That means, in the view, you should be using:

.content
 - if current_user.is_welcome == true
  Welcome to the site

Notice that it calls the method current_user instead of getting the @current_user instance variable.

If you need an instance variable, it is recommended that you have create a method current_user, which gets the instance variable and returns it.

I ended up doing this which let me keep the @current_user variable in my view and made the spec pass:

before :each do
  @user = stub_model(User, is_welcome: true)
  assign(:current_user, @user)
end

Then to test the conditionality, just ran another spec in a context with a different before block:

before :each do
  @user = stub_model(User, is_welcome: false)
  assign(:current_user, @user)
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!