请帮助解决问题。我使用gem'depaise',gem'rspec'和本教程:
 认证在Rspec测试中使用Devise 
 .i需要在控制台中输出@user。 
 emails_controller_spec.rb:


 RSpec.describe EmailsController,type :: controller do
 let(:valid_attributes){
 {
电子邮件:Faker :: Internet.email,
描述:Faker :: Lorem.paragraph(7),
 user_id:1
 }
 }

描述“GET #index”do
 login_user

它“将所有电子邮件分配为@emails”
 email = Email.create! valid_attributes
 get:index
 binding.pry
期待(分配(:电子邮件))。到eq([email])
 #expect(assigns(@user))。to eq(@user)
端
端&#XA末端
 代码>


 规格/工厂/ users.rb的:


 FactoryGirl.define do
工厂:用户做
序列(:电子邮件){| i | “us#{i }@ad.ad”}
密码'qwertyui'
 password_confirmation {| u | u.password}
角色:无
结束
结束



 spec / support / controller_macros.rb:


 module ControllerMacros
 def login_user
之前(:每个)做
 @ request.env [“devise.mapping”] = Devise.mappings [:user]
 user = FactoryGirl.create(:user)
 sign_in user
端
结束
结束



 i用户gem'prisy'用于在运行测试后从控制台查看变量。但我看到如下:


 kalinin @ kalinin~ / rails / mailer $ rspec spec / controllers

来自:/ home / kalinin / rails / mailer / spec / controllers / emails_controller_spec.rb @ line 56:
 [1] pry(#< RSpec :: ExampleGroups :: EmailsController :: GETIndex>)> @用户
 => nil
 [2] pry(#< RSpec :: ExampleGroups :: EmailsController :: GETIndex>)> user
 NameError:未定义的局部变量或#< RSpec :: ExampleGroups :: EmailsController :: GETIndex:0x00000007c4e670>
来自/home/kalinin/.rvm/gems/ruby-2.0的方法`user'。 0-p598 / gems / rspec-expectations-3.3.1 / lib / rspec / matchers.rb:966:在`method_missing'
 [3] pry(#< RSpec :: ExampleGroups :: EmailsController :: GETIndex&gt ;)> put page.html

 => nil



 我需要显示用户对象或显示页面的html代码。请帮助

答案 0 :(得分:0)
我希望您已将ControllerMacros
模块包含在某处。如果没有将其添加到emails_controller_spec.rb
文件的顶部include ControllerMacros
在前一个块中添加login_user
-
describe "GET #index" do
before { login_user }
it "assigns all emails as @emails" do
email = Email.create! valid_attributes
get :index
binding.pry
expect(assigns(:emails)).to eq([email])
expect(assigns(@user)).to eq(@user)
end
end
同时将ControllerMacros
更改为:
module ControllerMacros
def login_user
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
@user = FactoryGirl.create(:user)
sign_in @user
end
end
end