加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在rspec测试中创建一个对象变量但是没有

发布时间:2020-12-17 04:00:59 所属栏目:百科 来源:网络整理
导读:这是我的rspec代码: describe User do before{(@user=User.new(username:"abcdefg",email:"123456@123.com",password:"123456")} subject(@user) @user.saveend 我得到了这样一个错误:nil的未定义方法’save’:NilClass(NoMethodError) 我尝试在rails控制
这是我的rspec代码:

describe User do
  before{(@user=User.new(username:"abcdefg",email:"123456@123.com",password:"123456")}
  subject(@user)
  @user.save
end

我得到了这样一个错误:nil的未定义方法’save’:NilClass(NoMethodError)

我尝试在rails控制台中编写相同的代码,它只是起作用.但是当谈到Rspec时,它失败了,我找不到任何理由……

任何人都可以帮助我吗?

解决方法

您需要将代码包装在示例块中(即,使用块调用it方法),因为在describe块的上下文中,未定义@user.例如:

describe User do
  before{(@user=User.new(username:"abcdefg",password:"123456")}
  subject(@user)

  it "can be saved" do
    @user.should respond_to(:save)
    @user.save.should_not be_false
  end
end

编辑:我还注意到你有主题(@user),但可能需要是一个块才能正确设置它.以下是整体清洁:

describe User do
  let(:user) { User.new(username:"abcdefg",password:"123456") }

  it "can be saved" do
    user.should respond_to(:save)
    user.save.should_not be_false
  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读