未定义的方法`它的'对于RSpec(Hartl' Ruby on Rails教程)

时间:2015-01-18 19:42:46

标签: ruby-on-rails ruby rspec

我在Michael Hartl的RoR教程第8章中遇到了一个问题。测试失败,因为RSpec的“它”方法是“未定义的”。你见过类似的东西吗?可能是什么原因?我检查了一切,与书中的内容相同......

以下是来自user_spec.rb的测试代码:

describe User do

 before { @user = User.new(name: "Example User", email: "user@example.com",
                password: "foobar", password_confirmation: "foobar") }

 subject { @user }

 describe "remember token" do
 before { @user.save }
 its(:remember_token) { should_not be_blank }
end
...
...

测试运行的结果,它说:未定义的方法`它'用于RSpec :: ExampleGroups :: User :: RememberToken:Class(NoMethodError):

MBP:sample_app smi$ bundle exec rspec spec
/Users/smi/projects/sample_app/spec/models/user_spec.rb:12:in `block (2 levels) in <top (required)>': **undefined method `its' for RSpec::ExampleGroups::User::RememberToken:Class (NoMethodError)**
from /Users/smi/.rvm/gems/ruby-2.0.0-p594/gems/rspec-core-3.1.7/lib/rspec/core/example_group.rb:325:in `module_exec'
from /Users/smi/.rvm/gems/ruby-2.0.0-p594/gems/rspec-core-3.1.7/lib/rspec/core/example_group.rb:325:in `subclass'
from /Users/smi/.rvm/gems/ruby-2.0.0-p594/gems/rspec-core-3.1.7/lib/rspec/core/example_group.rb:219:in `block in define_example_group_method'
from /Users/smi/projects/sample_app/spec/models/user_spec.rb:10:in `block in <top (required)>'
from /Users/smi/.rvm/gems/ruby-2.0.0-p594/gems/rspec-core-3.1.7/lib/rspec/core/example_group.rb:325:in `module_exec'
from /Users/smi/.rvm/g.................

2 个答案:

答案 0 :(得分:11)

您将以下内容写为:

its(:remember_token) { should_not be_blank }

作为

expect(subject.remember_token).not_to be_blank

阅读its isn't core to RSpecArguments passed to its次讨论。当你使用Rspec&gt; = 3.0时,你就得到了错误。因为在此版本或更高版本中its不是Rspec核心的一部分。

您可以查看Rspec的当前One-liner syntax

答案 1 :(得分:2)

您需要安装gem 'rspec-its' - 它提供了方法作为简写来指定属性的预期值。