2014-02-19 82 views
0

我正在学习与Rails Tutorial的Rails。作者主动教授RSpec的选择位。在每章之后的练习中,您有机会学习编写密码。我选择了这些练习。但是,问题在于,在接下来的章节中,他将读者视为他们没有看到的东西,所以当你不知道如何适应他写的新的“不定式”代码时,你写的密码本身就会带来挑战这是'精明'的副本。Ruby on Rails RSPEC

在精粹版,文件的开头适合于少重复,看起来这样:

require 'spec_helper' 

    describe User do 

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

    subject { @user } 

    it { should respond_to(:name) } 
    it { should respond_to(:email) } 
    it { should respond_to(:password_digest) } 
    it { should respond_to(:password) } 
    it { should respond_to(:password_confirmation)} 

    it { should be_valid } 
    . 
    . 
    . 
end 

这样,那么我们的测试看起来像这样:

describe "when email is not present" do 
    before { @user.email = " " } 
    it { should_not be_valid } 
    end 

尝试当创建一个测试是否存在@user.password@user.password_confirmation,我期待继续这种RSpec格式。

作者版本看起来是这样的:

describe "when email is not present" do 
    before do 
    @user= User.new(name: "Example User", email: "[email protected]", 
        password: " ", password_confirmation = " ") 
    end 
    it { should_not be_valid } 
end 

我在它的尝试(因为提交恢复到做事而不pithier RSpec的代码运动的方法)将是这样:

describe "when password is not present" do 
    before { @user.password = " ", @user.password_confirmation = " " } 
    it { should_not be_valid } 
end 

这是在此上下文中使用before之前修改多个哈希值的正确方法吗?

此外,我正在努力找到我RSpec问题的答案。有没有人有寻找这些答案的可靠程序?

回答

1

通常情况下,如果你有一个块,占用了多条线路,你可以使用do...end代替{ },所以你的代码看起来像:

describe "when password is not present" do 
    before do 
    @user.password = " " 
    @user.password_confirmation = " " 
    end 
    it { should_not be_valid } 
end 

当寻找答案RSPEC相关的问题,我通常首先转向Google,但我会建议尝试缩小搜索范围(例如,如果您使用rSpec和Capybara,请查看Capybara文档,因为我还没有找到rSpec文档非常有用)。接下来我会看看这里(就像你一样),所以我认为你在正确的轨道上。

+0

太棒了,谢谢,这很有帮助!我正在使用水豚,所以我会看看他们的文档。另外,您是否需要用'{}'包围单行块,还是可以将它们关闭? – EnergyWasRaw

0

在作者版本中,它是before块还创建一个实例变量@user用于输入每个it描述。创建多个哈希值应该放在某些方法的参数中,如下所示: def some_method(args, hash_options = {})。将哈希参数放在方法中是一种红宝石风格,而不是将其放到Rspec before块中。在进入it块之前,before块用于实例化所需的执行。所以在你的情况下,我建议不要只在before块中放置多个散列值,而应该使用这些散列参数来准备一些对象实例化,以便可以在it块中运行该对象。

我建议读它有Rspec的概述:

日常的Rails测试在Rspec的
https://leanpub.com/everydayrailsrspec

在线资源:

更好的规格
http://betterspecs.org/