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

强颜欢笑 提交于 2019-12-06 16:00:04

问题


I have a view spec where I'm testing conditional output. How do I get the spec to return the user I've mocked out?

View file:

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

View spec:

before(:each) do 
  @user = mock_model(User)
  @user.stub!(:is_welcome).and_return(true)
  view.stub(:current_user).and_return(@user) 
end

it "show content" do 
  #assign(:current_user, stub_model(User, dismiss_intro: true))
  render
  rendered.should have_content("Welcome to the site")
end

Running the spec returns undefined method is_welcome for nil:NilClass


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/12329515/how-do-i-stub-out-a-current-users-attributes-in-a-view-spec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!