我正在尝试为我的rails应用程序编写一些视图规范,但我偶然发现了这个错误:
ActionView::Template::Error:
undefined local variable or method `current_user' for #<#<Class:0x007fa47d2612d0>:0x007fa47e267710>
以下是我编写视图规范的方法:
describe "/newsletters/index.html.erb" do
include NewslettersHelper
include Authlogic::TestCase
def current_user(stubs = {})
@current_user ||= mock_model(User, stubs)
end
def user_session(stubs = {}, user_stubs = {})
@current_user_session ||= mock_model(UserSession, {:user => current_user(user_stubs)}.merge(stubs))
end
def login(session_stubs = {}, user_stubs = {})
UserSession.stub!(:find).and_return(user_session(session_stubs, user_stubs))
end
def logout
@user_session = nil
end
context "without a logged-in user" do
before(:each) do
activate_authlogic
logout()
assigns[:newsletters] = @newsletters = [ mock_model(Newsletter, :titre => "value for titre",
:sommaire => "value for sommaire", :content => "value for content") ]
end
it "renders a list of newsletters" do
# pending("find how to mock authlogic current user in views spec")
render
rendered.should have_selector("tr>td") do |row|
row.should have_content("value for titre")
end
rendered.should have_selector("tr>td") do |row|
row.should have_content("value for sommaire")
end
rendered.should have_selector("tr>td") do |row|
row.should have_content("value for content")
end
end
端
答案 0 :(得分:1)
尝试controller.stub(:current_user) { mock_model(User) }
我认为应该有所帮助
答案 1 :(得分:1)
视图规范是一个独立的上下文,因此您需要在视图上下文中存根current_user方法。
view.stub(:current_user).and_return(mock_model(User))
如需进一步阅读查看规范,建议您view spec page津津乐道
答案 2 :(得分:0)
没有一个答案对我有用(在这里使用 rspec 3.9),因为我收到了像 #<#<Class:0x007fb9ca387dc8> does not implement: current_user
这样的错误,试图存根视图或控制器对象,所以我不得不这样做:
before do
controller.singleton_class.class_eval do
# Just defining methods to being stubbed later
def current_user; end
def current_account; end
helper_method :current_user, :current_account
end
allow(controller).to receive(:current_user).and_return(user)
allow(controller).to receive(:current_account).and_return(account)
end
不是最漂亮的解决方案,但它奏效了。