无法指定明确的“主题"? [英] Trouble on specifying explicit 'subject's?

查看:22
本文介绍了无法指定明确的“主题"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Ruby on Rails 3.0.9 和 RSpect 2.我试图通过以下方式重构一些规范文件(为了用更少的代码进行测试,类似 User 类对象属性值):

I am using Ruby on Rails 3.0.9 and RSpect 2. I am trying to refactoring some spec file in the following way (in order to test with less code similar User class object attribute values):

describe User do
  let(:user1) { Factory(:user, :users_attribute_a => 'invalid_value') }
  let(:user2) { Factory(:user, :users_attribute_b => 'invalid_value') }
  let(:user3) { Factory(:user, :users_attribute_c => 'invalid_value') }

  it "foreach user" do
    [ user1, user2, user3 ].each do |user|
      subject { user }

      it "should be whatever"
        user.should_not be_valid
        ...
      end
    end
  end
end

但是,如果我运行上述测试,则​​会出现以下错误:

However, if I run the above test I get the following error:

Failure/Error: it "should be whatever" do
  NoMethodError:
    undefined method `it' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_2::Nested_2:0x00000106ccee60>

有什么问题?我该如何解决?

UPDATE@Emily 回答之后.

如果在上面的代码中我使用 context "foreach user" do ... 而不是 it "foreach user" do ... 我得到以下错误:

If in the above code I use context "foreach user" do ... instead of it "foreach user" do ... I get the following error:

undefined local variable or method `user1' for #<Class:0x00000105310758> (NameError)

推荐答案

您正在混合和匹配各种 rspec 内容.这是你的东西,已修复:

You're mixing and matching all sorts of rspec stuff. Here's your stuff, fixed:

describe User do
  let(:user1) { Factory(:user, :users_attribute_a => 'invalid_value') }
  let(:user2) { Factory(:user, :users_attribute_b => 'invalid_value') }
  let(:user3) { Factory(:user, :users_attribute_c => 'invalid_value') }

  it "should not be valid" do
    [ user1, user2, user3 ].each do |user|
      user.should_not be_valid
    end
  end
end

我会这样做:

describe User do
  subject{Factory.build(:user)}
  it "should not be valid with invalid users_attribute_a" do
    subject.users_attribute_a = "invalid_value"
    subject.should_not be_valid
  end
  it "should not be valid with invalid users_attribute_b" do
    subject.users_attribute_b = "invalid_value"
    subject.should_not be_valid
  end
end

  • 如果你想拥有上下文",那就很酷了,但你不能在上下文中的上下文之前有变量.
  • 如果你想有一个规范,那就有一个,但你不能用它"声明
  • 用最少的代码更新

    describe User do
    
      it "should not be valid with other attributes" do
        {:users_attribute_a => 'invalid_value', :users_attribute_b => 'invalid_value', :users_attribute_c => 'invalid_value'}.each do |key, value|
          Factory.build(:user, key => value).should_not be_valid
        end
      end
    
    end
    

    这篇关于无法指定明确的“主题"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆