ruby-on-rails - RSpec 未定义的局部变量或方法

标签 ruby-on-rails ruby testing rspec

在 spec/controllers/profiles_controller_spec.rb 中出现奇怪的错误:未定义的局部变量或方法“profile”

粘贴在 Controller 的相关部分:

require 'rails_helper'
require 'factory_girl'

describe ProfilesController, :type => :controller do
  login_user #this is defined elsewhere, not an issue
  describe "PUT update" do
    before(:each) do
      @profile = FactoryGirl.create(:profile)
    end
    context "valid attributes" do
      it "located the requested @profile" do
        put :update, id: @profile, profile: FactoryGirl.attributes_for(:profile)
        assigns(:profile).should eq(@profile)
      end
    end
  end
end

最佳答案

我的猜测是您的规范或工厂没有问题。问题出在您正在测试的 Controller 上。

你看到的异常

1) ProfilesController PUT #update valid attributes located the requested @profile
   Failure/Error: put :update, id: @profile, profile: FactoryGirl.attributes_for(:profile)
   NameError:
     undefined local variable or method `profile' for #<ProfilesController:0x007fae343cfe08>

告诉您您的 ProfilesController 具有未定义的局部变量或方法 profile

在你的 Controller 中,你有这一行

if @profile.update(profile)

这很可能导致错误。也许您需要将 update(profile) 更改为 update(profile_params)?在没有看到整个 Controller 的情况下很难说清楚,但这会遵循一个共同的模式。我猜你有一个方法 profile_params 返回过滤后的参数。

关于ruby-on-rails - RSpec 未定义的局部变量或方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27495358/

相关文章:

ruby-on-rails - Mysql2::Error: PRIMARY KEY 的所有部分都必须为 NOT NULL;如果您需要在键中使用 NULL,请改用 UNIQUE

ruby - 检查数组是否是有序子集

ruby-on-rails - 错误 : rails aborted! LoadError : dlopen(/Users. ..但是是一个不兼容的架构(有 'x86_64' ,需要 'arm64e' ))

ruby - 运行 Ruby 脚本时更改 Bash 终端输出颜色

java - 如何立即从另一个线程使 TestNG 测试失败?

unit-testing - 如何在多个测试类中运行一组 junit 测试?

ruby-on-rails - Heroku : `SassC::SyntaxError: Error: Undefined variable: "$body-bg"` 上的 Rails 6

ruby-on-rails - 在 Rails 2.3.8 中登录不同的子域

unit-testing - 如何在单元测试 Nest.js 中测试抛出新的 HttpException

ruby-on-rails - 'rake db:seed' 能告诉你它阻塞在哪条记录上吗?