ruby-on-rails - `method_missing' : `build` is not available on an example group (e. 克。一个 `describe` 或 `context` block )

标签 ruby-on-rails unit-testing testing rspec rspec-rails

每次我想创建一个用户时,我都想删除 FactoryGirl.build(:user),所以我添加了这些行:

RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
end

spec_helper.rb。但这会产生以下错误:

`method_missing': `build` is not available on an example group (e.g. a `describe` or `context` block). It is only available from within individual examples (e.g. `it` blocks) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc). (RSpec::Core::ExampleGroup::WrongScopeError)

然后我删除了所有上下文/描述 block ,但这并没有改变任何东西。你们中有人遇到过同样的问题吗?我该如何解决?

目前我的测试是这样的:

require 'rails_helper'

RSpec.describe User, type: :model do
  user = build(:user)
  project = build(:project)

  it "is valid with a firstname, lastname, email and password" do
    expect(user).to be_valid
  end

  it "is invalid without a firstname" do
    user = build(:user, name: nil)

    expect(user.valid?).to be_falsey
    expect(user.errors[:name].size).to eq(1)
  end

  it "is invalid without a lastname" do
    user = build(:user, surname: nil)

    expect(user.valid?).to be_falsey
    expect(user.errors[:surname].size).to eq(1)
  end

  it "destroys dependent projects" do
    user = User.create!(name: 'john', surname: 'doe', email: 't@example.com', password: 'password', password_confirmation: 'password')
    user.projects << project

    expect{user.destroy}.to change {Project.count}.by(-1)
  end

end

最佳答案

代替:

user = build(:user)
project = build(:project)

做:

let(:user) { build(:user) }
let(:project) { build(:project) }

一般来说,定义外部变量以在测试中使用它们并不是一个好主意,因为这可能会使您的测试依赖于顺序并且极难调试。始终使用 let 语法,以便为每个测试重新初始化值。

关于ruby-on-rails - `method_missing' : `build` is not available on an example group (e. 克。一个 `describe` 或 `context` block ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28407798/

相关文章:

unit-testing - Mocking : Unit test question 中的依赖项太多

java - 使用 PowerMockito 测试 Unirest

reactjs - 我如何 Jest 测试使用上下文 api 的 react 组件?

ruby-on-rails - Rails 多个异常处理程序,每个路由命名空间为 "exceptions_app"

ruby-on-rails - 在 Rails_admin 自定义操作中重构 Ruby Proc 内的代码

ruby-on-rails - Rspec: nil.should_not be_nil 在我预期失败时通过。为什么?

java - 用于比较两个空对象的 junit 测试用例

ruby-on-rails - Bundler无法继续; "error occurred while installing mysql2 (0.4.5)"

ruby-on-rails - 为什么要使用 ActiveSupport::Concern 而不仅仅是一个普通的模块?

php - 如何使 PHPUnit 在有风险的测试中失败